在Java中初始化复杂静态成员的最佳方法是什么?

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)

看着它,它有效,但感觉不对.

你会怎么做?

Bal*_*usC 6

基本上有两种方式。第一种方法是使用静态块,如您所示(但随后使用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)


jar*_*bjo 5

我会抛出一个ExceptionInInitializerError而不是通用的RuntimeException,这是为了达到这个目的.从API文档:"表示静态初始化程序中发生了意外异常."