我的目标是拥有一个私人静态Properties
我的类中的对象,在创建其他对象时充当默认值Properties
我的应用程序所需的对象。当前的实现如下所示:
public class MyClass {
private static Properties DEFAULT_PROPERTIES = new Properties();
static {
try {
DEFAULT_PROPERTIES.load(
MyClass.class.getResourceAsStream("myclass.properties"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
看了下,确实可以,但是感觉不太对劲。
你会怎么做?
基本上有两种方法。第一种方法是使用静态块,如您所示(但随后使用ExceptionInInitializerError http://java.sun.com/javase/6/docs/api/java/lang/ExceptionInInitializerError.html而不是RuntimeException
)。第二种方法是使用静态方法,在声明时立即调用该方法:
private static Properties DEFAULT_PROPERTIES = getDefaultProperties();
private static Properties getDefaultProperties() {
Properties properties = new Properties();
try {
properties.load(MyClass.class.getResourceAsStream("myclass.properties"));
} catch (IOException e) {
throw new ConfigurationException("Cannot load properties file", e);
}
return properties;
}
The ConfigurationException
可以只是您的自定义类扩展RuntimeException
.
我个人更喜欢static
阻塞,因为执行一个方法是没有意义的只有一次永远在它的生命中。但是,如果您重构该方法,使其采用文件名并且可以在全局范围内重用,那么这将是更优选的。
private static Properties DEFAULT_PROPERTIES = SomeUtil.getProperties("myclass.properties");
// Put this in a SomeUtil class.
public static Properties getProperties(String filename) {
Properties properties = new Properties();
try {
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename));
} catch (IOException e) {
throw new ConfigurationException("Cannot load " + filename, e);
}
return properties;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)