JavaSwitch語句:常量表達(dá)式是必需的,但它是常量所以,我正在研究這個(gè)類,它有幾個(gè)靜態(tài)常量:public abstract class Foo {
...
public static final int BAR;
public static final int BAZ;
public static final int BAM;
...}然后,我想要一種基于常量獲得相關(guān)字符串的方法:public static String lookup(int constant) {
switch (constant) {
case Foo.BAR: return "bar";
case Foo.BAZ: return "baz";
case Foo.BAM: return "bam";
default: return "unknown";
}}但是,當(dāng)我編譯時(shí),我會(huì)得到一個(gè)constant expression required三個(gè)大小寫標(biāo)簽上的每個(gè)錯(cuò)誤。我知道編譯器需要在編譯時(shí)知道表達(dá)式才能編譯一個(gè)開關(guān),但為什么不知道呢?Foo.BA_常量?
3 回答

倚天杖
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
public abstract class Foo { ... public static final int BAR=0; public static final int BAZ=1; public static final int BAM=2; ...}

隔江千里
TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
public static final int TAKE_PICTURE = 1;
public static int TAKE_PICTURE = 1;
添加回答
舉報(bào)
0/150
提交
取消