在 Java 中初始化复杂静态成员的最佳方法是什么?
我的目标是在我的类中拥有一个私有静态 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);
}
}
}
看看它,它可以工作,但感觉不太对劲。
你会怎么做?
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.
How would you do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本上有两种方法。第一种方法是使用静态块,如您所示(但随后使用
ExceptionInInitializerError
而不是RuntimeException
)。第二种方法是使用在声明时立即调用的静态方法:ConfigurationException
可以只是扩展RuntimeException
的自定义类。我个人更喜欢
static
块,因为拥有一个在其生命周期中仅执行一次的方法是没有意义的。但是,如果您重构该方法,使其采用文件名并且可以在全局范围内重用,那么这将是更优选的。There are basically two ways. First way is using the static block as you have shown (but then with an
ExceptionInInitializerError
instead of theRuntimeException
). Second way is using a static method which you call immediately on declaration:The
ConfigurationException
can just be your custom class extendingRuntimeException
.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.我不会抛出通用的 RuntimeException,而是抛出 ExceptionInInitializerError< /a>,正是为了这个目的而进行的。来自 API 文档:“表示静态初始值设定项中发生意外异常的信号。”
Instead of a generic RuntimeException, I would throw an ExceptionInInitializerError, which is ment for exacctly this purpose. From the API documentation: "Signals that an unexpected exception has occurred in a static initializer."
对我来说似乎可以接受; load 到静态初始化器中,只有在类被引用时才会被调用,并且只被调用一次。我喜欢它。我唯一要做的就是将其定为
最终
。好吧,除了例外。我会尝试以某种方式避免这种情况(我内心深处认为你应该避免这些类型的初始化程序中的异常,但我可能是错的)。
Seems acceptable to me; load in the static initialiser, it gets called only when the class is referenced, and is only called once. I like it. The only thing I'd do is make it
final
.Well, aside from the exception. I'd try and avoid that somehow (I have in the back of my mind that you should avoid exceptions in those types of initialisers, but I could be wrong on that).