假设我有以下枚举:
public enum BooleanEnum {
FALSE(false), TRUE(true);
private BooleanEnum(boolean value) {
this.value = value;
}
private final boolean value;
public boolean value() {
return value;
}
}
Java 会从编译后的代码中删除以下代码吗?
if (BooleanEnum.FALSE.value()) {
//would the contents here get removed?
}
我知道如果我使用静态最终常量就会出现这种情况,例如:
static final boolean DEBUG = false;
if (DEBUG) { x=3; }
Java 编译器会删除 if (DEBUG) { x=3; }
代码。
如果上面的枚举代码没有被删除,是否有任何方法可以在不返回静态常量的情况下实现它?
最佳答案
我假设您已经阅读过 JLS #14.21 .
Would Java remove the following code from the compiled code?
if (BooleanEnum.FALSE.value()) {
//would the contents here get removed?
}
没有。因为 value()
不是编译时常量值。它可能返回 true
或 false
。请参阅以下代码片段。
static enum BooleanEnum {
FALSE(false), TRUE(true);
private BooleanEnum(boolean value) {
this.value = value;
}
private final boolean value;
public boolean value() {
if (System.currentTimeMillis() % 2 == 0) {
return true;
} else {
return false;
}
}
}
编译器在编译过程中不进行逻辑分析。而static final boolean DEBUG = false
在编译期间显然是恒定的,并且可以用于条件编译
目的。
If the enum code above does not get removed, would there be any way to make it so without going back to static constants?
使用静态常量是唯一的方法。
根据您想要实现的目标,可能还有其他解决方案。例如使用一个简单的类文件,该文件在编译前根据您的情况生成。
public class CompileFlag {
static final boolean DEBUG = false;
}
关于java - Java 编译器是否删除了检查枚举常量的无法访问的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36417816/