在静态 try-catch 中分配静态最终变量

assign static final variable in a static try-catch

我想读取配置文件的 属性 并将其分配给 static final 变量,如果配置文件 omit/or 不存在,则使用默认值 hard-编码。

public static final String NOTIFY_ALI;
static  {
    try {
        PropertyReader notifyConf = new PropertyReader("notify.conf");
        NOTIFY_ALI = notifyConf.getProperty("notify_ali","http://notify.foo.com/notify");

    } catch (IOException e) {
        e.printStackTrace();
        NOTIFY_ALI = "http://notify.foo.com/notify";
    }
}

NOTIFY_ALI 应该由配置文件 notify.conf 使用键 notify_ali 分配,或者如果它在文件中不明确,则将 http://notify.foo.com/notify 作为默认值。如果配置文件不存在(IOException 会发生),只需捕获异常并分配默认值。

但是上面的代码片段给出了一个编译时间错误:

Error:(18, 13) java: variable NOTIFY_ALI might already have been assigned

我可以这样做吗?

创建一个 returns URL 的方法,并在声明时使用它来赋值

public static final String NOTIFY_ALI = getURL() ;

private static String getURL()
{ 
    String aux ;

    try {
        PropertyReader notifyConf = new PropertyReader("notify.conf");
        aux = notifyConf.getProperty("notify_ali","http://notify.foo.com/notify");

    } catch (IOException e) {
        e.printStackTrace();
        aux = "http://notify.foo.com/notify";
    }
    return aux ; 
}

如果你需要初始化多个变量,你可以这样做

public static final InitVariables IV = initVariables() ;

public class InitVariables {
    String NOTIFY_ALI ;
    String CONTACT_EMAIL ;
    int numEmployees ; 
}

private static InitVariables initVariables()
{ 
    InitVariables iv ;

    iv = new InitVariables() ;

    try {
        PropertyReader notifyConf = new PropertyReader("notify.conf");
        aux = notifyConf.getProperty("notify_ali","http://notify.foo.com/notify");

    } catch (IOException e) {
        e.printStackTrace();
        aux = "http://notify.foo.com/notify";
    }

    iv.NOTIFY_ALI = aux ;

    iv.CONTACT_EMAIL = "you@somedomain.com";
    iv.numEmployees = 0 ;

    return iv ; 
}

你为什么不删除静态初始化块并创建一个静态方法,其结果分配给你的静态最终变量?

public static final String NOTIFY_ALI = init();

private static String init() {
    try {
        PropertyReader notifyConf = new PropertyReader("notify.conf");
        return  notifyConf.getProperty("notify_ali","http://notify.foo.com/notify");
    } catch (IOException e) {
        e.printStackTrace();
        return "http://notify.foo.com/notify";
    }
}