在Java中初始化复杂静态成员的最佳方法是什么? [英] What is the best way to initialize a complex static member in Java?
问题描述
我的目标是在我的类中拥有一个私有静态属性
对象,在创建其他属性
我的应用程序所需的对象。当前的实现如下所示:
My objective is to have a private static Properties
object in my class, to act as defaults when creating other Properties
objects needed by my application. The current implementation looks like this:
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);
}
}
}
看着它,它有效,但感觉不对。
Looking at it, it works, but it doesn't feel right.
你会怎么做?
推荐答案
基本上有两种方式。第一种方法是使用你所显示的静态块(但随后使用 ExceptionInInitializerError
而不是 RuntimeException
)。第二种方法是使用静态方法,您可以在声明时立即调用:
There are basically two ways. First way is using the static block as you have shown (but then with an ExceptionInInitializerError
instead of the RuntimeException
). Second way is using a static method which you call immediately on declaration:
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
。
The ConfigurationException
can just be your custom class extending RuntimeException
.
我个人更喜欢 static
阻止,因为拥有一个在其生命中只执行一次的方法是没有意义的。但是如果你重构方法以便它采用文件名并且可以全局重用,那么这将是更优选的。
I personally prefer the static
block because it doesn't make sense having a method which is executed only once ever in its life. But if you refactor the method so that it takes a filename and can be reused globally, then that would be more preferred.
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;
}
这篇关于在Java中初始化复杂静态成员的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!