我正在尝试初始化一个静态最终变量。但是,这个变量是在一个可以抛出异常的方法中初始化的,因此,我需要在一个 try catch block 中。
即使我知道变量将在 try 或 catch block 上初始化,java 编译器也会产生错误
The final field a may already have been assigned
这是我的代码:
public class TestClass {
private static final String a;
static {
try {
a = fn(); // ERROR
} catch (Exception e) {
a = null;
}
}
private static String fn() throws Exception {
throw new Exception("Forced exception to illustrate");
}
}
我尝试了另一种方法,直接将其声明为 null,但它显示了类似的错误(在这种情况下,这对我来说似乎完全合乎逻辑)
The final field TestClass.a cannot be assigned
public class TestClass {
private static final String a = null;
static {
try {
a = fn(); // ERROR
} catch (Exception e) {
}
}
private static String fn() throws Exception {
throw new Exception("Forced exception to illustrate");
}
}
有没有优雅的解决方案?
最佳答案
可以先将值赋值给局部变量,然后在try
-catch
block 之后赋值给final
变量:
private static final String a;
static {
String value = null;
try {
value = fn();
} catch (Exception e) {
}
a = value;
}
这确保了对 final
变量的单一赋值。
关于java - 无法在 try/catch 中初始化静态最终变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49977427/