今天使用swith語句時,調用定義好的常量時,編譯報錯:case expressions must be constant expression。html
常量類以下:java
public class Constants{ public static final Integer HIGH=5; public static final Integer MEDIUM=3; public static final Integer LOW=1; }
調用以下:express
switch(level){ case Constants.HIGH: …… case Constants.MEDIUM: …… case Constants.LOW: …… }
後來查了下,有人說定義常量時,常量要是static final.這個個人定義裏已是了,但仍然報錯,最後仍是查到一個英文的答案,說是要使用基本數據類型,不能使用包裝類,即其only be applied to primitives and Strings,因此改爲以下定義:app
public class Constants{ public static final int HIGH=5; public static final int MEDIUM=3; public static final int LOW=1; }
至此問題解決。ide
附:參考答案:http://www.coderanch.com/t/329474/java/java/final-static-Integer-considered-constant this
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.spa