Can';t访问交换机案例/Java中的枚举值

Can';t访问交换机案例/Java中的枚举值,java,enums,switch-statement,Java,Enums,Switch Statement,我无法访问switch case语句中的枚举变量: public enum Country { FRANCE(0, "France"), SPAIN(1, "Spain"); private final int code; private final String name; Country(int code, String name) { // TODO Auto-generated constructor stub this.code = code; this.na

我无法访问switch case语句中的枚举变量:

public enum Country {

FRANCE(0, "France"), SPAIN(1, "Spain");
private final int code;
private final String name;
Country(int code, String name) {
    // TODO Auto-generated constructor stub
    this.code = code;
    this.name = name;
}
public int getCode() {
    return code;
}
public String getName() {
    return name;
}
}
在另一个类中,有以下代码:

public Drawable getFlag(){
    Drawable d = null;
    switch(country_id){
    case Country.FRANCE.getCode():
        break;
    }
    return d;
}

但问题是,当我键入Country时,只有class或this。

case
语句中的标签必须是常量

case表达式必须是编译时常量表达式。枚举实例的变量是常量,但不是编译时常量

我们称一个变量为原语类型或字符串类型,即final 并用编译时常量表达式(§15.28)初始化 常量变量。变量是否为常量变量 可能对类别初始化有影响(§12.4.1), 二进制兼容性(§13.1,§13.4.9)和定赋值(§16)


case
语句中的表达式必须是常量。 解决问题的一种(常用)方法是创建一个从数字代码获取枚举的函数:

public enum Country {
...
public static Country getCountry(int countryCode) {
    for(Country country : Country.values()) {
        if(country.code == countryCode) {
            return country;
        }
    }
    throw new IllegalArgumentException();
}
然后,您可以在枚举上进行切换:

switch(Country.getCountry(country_id)){
case Country.FRANCE:
    break;
...
}