public class Test1 {
static final int i;
static{
if(3<2){
i = 0;
}
}
}
public class Test2 {
static final int i;
static{
if(3>2){
i = 0;
}
}
}
类 Test1
编译失败,
类 Test2
编译成功。
任何人都可以告诉我编译器如何能够在 if 条件下评估表达式吗?
最佳答案
static final int i;
需要在静态初始化器中初始化,因为它是最终的。
static{
if(3<2){
i = 0;
}
}
由于 3<2 字面值或常量,编译器能够检测到代码的无效部分并且不会初始化 i。
添加一个 else
案例并在那里做一些 i
初始化。
关于java - 可以在编译时评估表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13786424/