所以,我正在处理这个类,它有几个静态常数:

public abstract class Foo {
    ...
    public static final int BAR;
    public static final int BAZ;
    public static final int BAM;
    ...
}

然后,我想要一种方法来获得一个基于常量的相关字符串:

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

然而,当我编译时,我在3个case标签上都得到了一个常量表达式所需的错误。

我知道编译器需要表达式在编译时编译开关,但为什么不是Foo。BA_常数?


当前回答

问题是整型和整数(我不知道为什么),改变整型字符串和它的工作

public abstract class Foo {
    ...
    public static final String BAR;
    public static final String BAZ;
    public static final String BAM;
    ...
}
public static String lookup(String constant) {
    switch (constant) {
        case Foo.BAR: return "bar";
        case Foo.BAZ: return "baz";
        case Foo.BAM: return "bam";
        default: return "unknown";
    }
}

其他回答

因为这些不是编译时常数。考虑以下有效代码:

public static final int BAR = new Random().nextInt();

您只能在运行时知道BAR的值。

问题是整型和整数(我不知道为什么),改变整型字符串和它的工作

public abstract class Foo {
    ...
    public static final String BAR;
    public static final String BAZ;
    public static final String BAM;
    ...
}
public static String lookup(String constant) {
    switch (constant) {
        case Foo.BAR: return "bar";
        case Foo.BAZ: return "baz";
        case Foo.BAM: return "bam";
        default: return "unknown";
    }
}

我在Android上得到了这个错误,我的解决方案就是使用:

public static final int TAKE_PICTURE = 1;

而不是

public static int TAKE_PICTURE = 1;

有时switch变量也会犯这样的错误,例如:

switch(view.getTag()) {//which is an Object type

   case 0://will give compiler error that says Constant expression required

   //...
}

要解决这个问题,你应该将变量转换为int(在这种情况下)。所以:

switch((int)view.getTag()) {//will be int

   case 0: //No Error

   //...
}

您需要常量表达式,因为您没有使用常量的值。试一试:

public abstract class Foo {
    ...
    public static final int BAR=0;
    public static final int BAZ=1;
    public static final int BAM=2;
    ...
}