case表达式必须是static final int的常量表达式? [英] Case expressions must be constant expressions for static final int?
问题描述
我有一个最终类Ring
定义为:
final class Ring {
public static final int OUT = 3;
public static final int MID = 2;
public static final int IN = 1;
}
我还有公共类MorrisBoard
使用以下代码:
public class MorrisBoard {
public static final Ring RING = new Ring();
private boolean checkMillBy(int ring, int x, int y) {
switch(ring) {
case MorrisBoard.RING.OUT:
//...
case MorrisBoard.RING.MID: //etc.
//...
}
return false;
}
MorrisBoard.RING.OUT
引用一个在程序生命周期内不可变的变量。所有价值都是最终的。
MorrisBoard.RING.OUT
references a variable which is immutable for the lifetime of the program. All values are final.
但是,我仍然会收到以下错误: case表达式必须是常量表达式
。我对此感到困惑 - MorrisBoard.RING.OUT
是一个常量表达式。
However, I still get the following error: case expressions must be constant expressions
. I'm confused by this - MorrisBoard.RING.OUT
is a constant expression.
这里发生了什么?
推荐答案
替换
case MorrisBoard.RING.OUT:
with
case Ring.OUT:
所以这将是一个常数,如编译时确定。
So this will really be a constant as in "determined at compilation".
规范精确SwitchLabel必须是
The specification precises that a "SwitchLabel" must be
-
案例
后跟一个常量表达式 -
case
后跟枚举值的名称 - 或
默认
case
followed by a constant expressioncase
followed by the name of an enum value- or
default
什么是有效的常量表达式在规范中描述。它相当有限。
What is considered a valid constant expression is described here in the specification. It's fairly limited.
这篇关于case表达式必须是static final int的常量表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!