【问题标题】:switch-case with a string and enum in javajava中带有字符串和枚举的switch-case
【发布时间】:2020-12-09 19:03:52
【问题描述】:

我想使用 switch-case 在 java 中检查一个带有 enum 值的字符串,所以我这样做了:

public enum DemoEnumType {

    ALL(""),
    TOP("acb"),
    BOTTOM("def");

    private String code;

    DemoEnumType(String code) {
        this.code = code;
    }

    public String code() {
        return this.code;
    }


}

当我运行这段代码时,它会抛出一个异常:

public class Demo {
    public static void main(String[] args) {
        DemoEnumType typeValue = DemoEnumType.valueOf("acb");
        
        switch (typeValue){
            case ALL:
                System.out.print("match");
            case BOTTOM:
                System.out.print("match");
            case TOP:
                System.out.print("match");
        }

    }
}

例外:

线程“main”java.lang.IllegalArgumentException 中的异常:没有枚举常量 package.DemoEnumType.acb。

【问题讨论】:

  • 你的底句是什么意思?你能把它翻译成英文吗?抛出什么异常?你能发布堆栈跟踪吗?
  • 是的。我已经更正了帖子,这是一个例外
  • 还有:别忘了使用break;声明

标签: java android string enums switch-statement


【解决方案1】:
DemoEnumType typeValue = DemoEnumType.valueOf("acb");

不存在值为acb 的枚举元素。如果给定的name 不存在任何元素,Enum#valueOf 将抛出一个IllegalArgumentException。您需要使用ALLBOTTOMTOP

DemoEnumType type = DemoEnumType.valueOf("ALL");

或者,您可以使用 String 到 DemoEnumType 的 Map 进行 O(1) 查找并使用您提供的值。

Map<String, DemoEnumType> valueToType = Stream.of(DemoEnumType.values())
        .collect(Collectors.toMap(DemoEnumType::code, Function.identity());

DemoEnumType type = valueToType.get("abc");

【讨论】:

    【解决方案2】:

    您的 Enum 成员是 ALL、TOP 和 BOTTOM,而不是字符串值。您只能将 then 传递给 valueOf()。

    要使用字符串值,您可以在 Enum 中创建一个接收字符串并返回适当 Enum 的方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      • 2021-10-09
      • 2011-12-27
      • 1970-01-01
      相关资源
      最近更新 更多