switch-case与java中的字符串和枚举

i5desfxk  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(410)

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

  1. public enum DemoEnumType {
  2. ALL(""),
  3. TOP("acb"),
  4. BOTTOM("def");
  5. private String code;
  6. DemoEnumType(String code) {
  7. this.code = code;
  8. }
  9. public String code() {
  10. return this.code;
  11. }
  12. }

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

  1. public class Demo {
  2. public static void main(String[] args) {
  3. DemoEnumType typeValue = DemoEnumType.valueOf("acb");
  4. switch (typeValue){
  5. case ALL:
  6. System.out.print("match");
  7. case BOTTOM:
  8. System.out.print("match");
  9. case TOP:
  10. System.out.print("match");
  11. }
  12. }
  13. }

例外:
线程“main”java.lang.illegalargumentexception中出现异常:没有枚举常量package.demoenumtype.acb。

to94eoyn

to94eoyn1#

枚举成员是all,top和bottom,而不是字符串值。只能传递给valueof()。
要使用字符串值,可以在枚举中创建一个方法,该方法接收字符串并返回相应的枚举

mklgxw1f

mklgxw1f2#

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

不存在具有该值的枚举元素 acb . Enum#valueOf 将抛出一个 IllegalArgumentException 如果给定的 name . 你需要使用 ALL , BOTTOM ,或 TOP .

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

或者,您可以使用字符串Mapdemoenumtype进行o(1)查找,并使用您提供的值。

  1. Map<String, DemoEnumType> valueToType = Stream.of(DemoEnumType.values())
  2. .collect(Collectors.toMap(DemoEnumType::code, Function.identity());
  3. DemoEnumType type = valueToType.get("abc");

相关问题