【问题标题】:How to use String enums in switch statement? [duplicate]如何在 switch 语句中使用字符串枚举? [复制]
【发布时间】:2015-06-16 23:05:59
【问题描述】:
public class TestingGen {

    /**
     * @param args
     */

    public enum Types {

        TYPE1("TYPE1"), TYPE2("TYPE2");

        private String type;

        private Types(String type) {
            this.type = type;
        }

        public String getType() {
            return type;
        }
    }

    public static void main(String[] args) {

        String value = null;
        switch (value) {
        case Types.TYPE1.getType():
            System.out.println("here");
            break;
        case Types.TYPE2.getType():
            System.out.println("there");
        default:
            System.out.println("default");
        }
    }

}

它在两个 case 语句中都显示错误“case 表达式必须是常量表达式”。

那么如何在 swtich 语句中使用字符串枚举呢?

【问题讨论】:

标签: java enums switch-statement


【解决方案1】:

公共类TestingGen {

/**
 * @param args
 */

public enum Types {

    TYPE1("TYPE1"), TYPE2("TYPE2");
     String type = null;

    Types(String s) {
        type = s;
    }

     String getType() {
        return type;
    }
}

public static void main(String[] args) {

    for(Types value : Types.values()) { 
        System.out.println(value + "  " + value.getType() + " ");
     }

}

}

【讨论】:

  • 我想在 swtich 案例中使用枚举。
【解决方案2】:

反过来。获取字符串Types enumValue = Types.valueOf(stringValue) 的枚举值并打开枚举值switch(enumValue) { case TYPE1: [...]

【讨论】:

  • Types.valueOf() ,给出无效值的异常,如何处理这种情况
  • 捕获异常,将default 案例代码放在catch 块中。
  • hmm... 在 swtich 中使用枚举的任何其他方式
  • 枚举值的字符串值不是恒定的,它们是在构造枚举值期间设置的。因此,它们不能用作 case 表达式。这是设计使然,我不知道有什么办法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
相关资源
最近更新 更多