2

我的目标是在我的类中有一个私有静态对象,在创建我的应用程序所需的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);
        }
    }
 }

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

你会怎么做?

4

3 回答 3

6

基本上有两种方式。第一种方法是使用您所展示的静态块(但随后使用 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;
}
于 2010-01-08T12:09:39.517 回答
5

我会抛出一个ExceptionInInitializerError ,而不是一个通用的 RuntimeException ,这正是为了这个目的。来自 API 文档:“表示静态初始化程序中发生了意外异常的信号。”

于 2010-01-08T11:52:57.640 回答
0

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).

于 2010-01-08T11:37:46.860 回答