各位大侠好,小弟最近写了一个spring读取配置文件的工具类,出现以下问题,希望各位不吝赐教~ 拜谢!
代码如下:
public class PropertieUtil { private static Properties properties; private PropertieUtil() { try { System.out.println("once"); properties = PropertiesLoaderUtils .loadAllProperties("parameter.properties"); } catch (IOException e) { } } private static class PropertieUtilFactory { private static final PropertieUtil instance = new PropertieUtil(); } @SuppressWarnings("static-access") public static String getPropertie(String key) { // 这种不加括号的报错:java.lang.NullPointerException,是因为没走构造函数,为什么不走构造函数呢?? // return PropertieUtilFactory.instance.properties.getProperty(key); // 这种加括号的可以,为什么呢? return (PropertieUtilFactory.instance).properties.getProperty(key); } }
再次,如果按照目前这样写的,以下只是我的理解,不一定正确
1. 不加括号,PropertieUtilFactory.instance.properties.getProperty(key);
因为properties是static的,前面的PropertieUtilFactory.instance仅仅表示这个方法所在的路径而不会做任何处理
2. 加括号 (PropertieUtilFactory.instance).properties.getProperty(key);
由于括号优先级高,编译时认为这里要用到PropertieUtilFactory.instance而对instance进行实例化,之后再访问properties