类静态初始化块内的类用法

时间:2013-11-06 11:32:42

标签: java class static

可能会在某处讨论,但我找不到它。

我需要在类静态初始化块中加载类属性(java.util.Properties)。这样即使没有创建对象,也可以访问某些类通用选项。为此,我需要适当的Class对象。但是当然对null对象访问此类对象失败了。这样的事情。

Class Name {

    private static Properties properties;

    static {
        Name.properties = new Properties();
        Name.properties.load(Name.class.getResourceAsStream("Name.properties"));
    }

}

知道如何处理这种情况吗?

更新:
它是资源名称(对于我的情况应该是“/Name.properties”)。其他一切都还可以。 +1来自我的所有有意义的答案......不要忘记逐一检查操作: - )。

3 个答案:

答案 0 :(得分:3)

properties字段必须为static。在load之前,您需要使用proeprties = new Properties()初始化静态变量,之后您可以调用load

答案 1 :(得分:1)

将属性声明为static并初始化

static Properties properties;

static Properties properties = new Properties();

和静态块应该是

static {
    try {
        properties = new Properties(); //if you have not initialize it already
        Name.properties.load(Name.class.getResourceAsStream("Name.properties"));
    } catch (IOException e) {
        throw new ExceptionInInitializerError(e); //or some message in constructor
    }
}

加载属性文件时需要捕获IOException

答案 2 :(得分:0)

基于所有建议的最终代码如下:

Class Name {

    private static final Properties properties = new Properties();

    static {
        try {
            InputStream stream = Name.class.getResourceAsStream("/Name.properties");
            if (stream == null) {
                throw new ExceptionInInitializerError("Failed to open properties stream.");
            }
            Name.properties.load(stream);
        } catch (IOException e) {
            throw new ExceptionInInitializerError("Failed to load properties.");
        }
    }
}
相关问题