Igo*_*gor 1 java static-members
我的目标是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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
看着它,它有效,但感觉不对.
你会怎么做?
基本上有两种方式。第一种方法是使用静态块,如您所示(但随后使用ExceptionInInitializerError代替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;
}
Run Code Online (Sandbox Code Playgroud)
本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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
734 次 |
| 最近记录: |