基本上有两种方式。第一种方法是使用您所展示的静态块(但随后使用 aExceptionInInitializerError
而不是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;
}
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;
}