带有Java中的字符串和枚举的switch-case

时间:2020-08-20 12:29:14

标签: java android string enums switch-statement

我想使用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。

2 个答案:

答案 0 :(得分:1)

DemoEnumType typeValue = DemoEnumType.valueOf("acb");

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

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

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

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

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

答案 1 :(得分:1)

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

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

相关问题