[英]switch-case with a string and enum in java
我想使用 switch-case 检查 java 中枚举值的字符串,所以我这样做了:
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");
}
}
}
例外:
线程“主”java.lang.IllegalArgumentException 中的异常:没有枚举常量 package.DemoEnumType.acb。
DemoEnumType typeValue = DemoEnumType.valueOf("acb");
不存在值为acb
的枚举元素。 如果不存在具有给定name
的元素,则Enum#valueOf
将抛出IllegalArgumentException
。 您需要使用ALL
、 BOTTOM
或TOP
。
DemoEnumType type = DemoEnumType.valueOf("ALL");
或者,您可以使用字符串的 Map 到 DemoEnumType 进行 O(1) 查找并使用您提供的值。
Map<String, DemoEnumType> valueToType = Stream.of(DemoEnumType.values())
.collect(Collectors.toMap(DemoEnumType::code, Function.identity());
DemoEnumType type = valueToType.get("abc");
您的枚举成员是 ALL、TOP 和 BOTTOM,而不是字符串值。 您只能将其传递给 valueOf()。
要使用字符串值,您可以在 Enum 中创建一个接收字符串并返回适当 Enum 的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.