简体   繁体   English

Java编译器是否删除检查枚举常量的if语句?

[英]Does the Java compiler remove unreachable if statements that check for enum constants?

Suppose I have the following enum: 假设我有以下枚举:

public enum BooleanEnum {
   FALSE(false), TRUE(true);
   private BooleanEnum(boolean value) {
       this.value = value;
   }
   private final boolean value;
   public boolean value() {
       return value;
   }
}

Would Java remove the following code from the compiled code? Java是否将从已编译的代码中删除以下代码?

if (BooleanEnum.FALSE.value()) {
     //would the contents here get removed?
}

I know this would be the case if I were using static final constants, for example in: 我知道如果我使用静态最终常量,例如:

static final boolean DEBUG = false;
if (DEBUG) { x=3; }

The Java compiler would remove the if (DEBUG) { x=3; } Java编译器将删除if (DEBUG) { x=3; } if (DEBUG) { x=3; } code. if (DEBUG) { x=3; }代码。

If the enum code above does not get removed, would there be any way to make it so without going back to static constants? 如果上面的枚举代码没有被删除,是否有任何方法可以做到,而无需返回静态常量?

I assume you read already JLS #14.21 . 我假设您已经阅读了JLS#14.21

Would Java remove the following code from the compiled code? Java是否将从已编译的代码中删除以下代码?
if (BooleanEnum.FALSE.value()) { 如果(BooleanEnum.FALSE.value()){
//would the contents here get removed? //这里的内容会被删除吗?
} }

No. Because value() is not a compile time constant value. 否。因为value()不是编译时间常数值。 It could return true or false . 它可能返回truefalse See following snippet. 请参阅以下代码段。

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;
        }
    }
}

The compiler does no logical analysis during the compilation. 编译器在编译期间不进行逻辑分析。 Wheras static final boolean DEBUG = false is clearly constant during the compile time and could be used for conditional compilation purpose. Wheras static final boolean DEBUG = false在编译期间显然是常量,可以用于conditional compilation

If the enum code above does not get removed, would there be any way to make it so without going back to static constants? 如果上面的枚举代码没有被删除,是否有任何方法可以做到,而无需返回静态常量?

Using static constants is the only way. 使用静态常量是唯一的方法。

Depending what you want to achieve there could be other solutions. 根据您要实现的目标,可能会有其他解决方案。 eg using a simple class file which is generated before the compilation based on your conditions. 例如,使用一个简单的类文件,该文件根据您的条件在编译之前生成。

public class CompileFlag {
    static final boolean DEBUG = false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM