case expressions must be constant expression

今天使用swith语句时,调用定义好的常量时,编译报错:case expressions must be constant expression。

常量类如下:

public class Constants{
    public static final Integer HIGH=5;
    
     public static final Integer MEDIUM=3;
     
      public static final Integer LOW=1;
}

调用如下:

switch(level){
    case Constants.HIGH:
    ……
    
    case Constants.MEDIUM:
    ……
    case Constants.LOW:
    ……
}

后来查了下,有人说定义常量时,常量要是static final.这个我的定义里已经是了,但仍然报错,最后还是查到一个英文的答案,说是要使用基本数据类型,不能使用包装类,即其only be applied to primitives and Strings,所以改成如下定义:

public class Constants{
    public static final int HIGH=5;
    
     public static final int MEDIUM=3;
     
      public static final int LOW=1;
}

至此问题解决。

附:参考答案:http://www.coderanch.com/t/329474/java/java/final-static-Integer-considered-constant

Yes. Case statements can only take compile-time constants, or enums, and the definition of compile-time constant expressions can only be applied to primitives and Strings. That's just the way they wrote the rules. On the one hand, yes the compiler has access to enough information here that it could probably figure out how to use an int rather than an Integer here. On the other hand, there's really no reason this number needs to be an Integer in the first place, is there? It can easily be changed to an int, and everything will work fine.

你可能感兴趣的:(case expressions must be constant expression)