如何匹配和切换字符串与枚举?

时间:2013-10-24 13:19:56

标签: java enums

我想将String转换为枚举。但是如何?

class Letter {
    A, B, C
}

String letter = "A";
switch (letter) {
    case Letter.A: //cannot convert from Letter to String
    case Letter.A.toString(): //case expressions must be constant expressions
    case Letter.C.name(): //case expressions must be constant expressions
    default:
}

5 个答案:

答案 0 :(得分:5)

首先Letter必须是枚举:

enum Letter {
    A, B, C
}

Letter letter = Letter.valueOf("A")
// and just switch
switch (letter) {
    case A:
    case B:
    case C:
}

答案 1 :(得分:3)

你可以这样做:

String letter = "A";
switch (Letter.valueOf(letter)) {
    case A: // No problem!
    case B:
    case C:
    default:
}

Demo on ideone

答案 2 :(得分:2)

首先使用枚举而不是Class 替换为

Letter obj = Letter.valueOf(letter);
switch (obj) {
    case A: //cannot convert from Letter to String
    case B: //case expressions must be constant expressions
    case C: //case expressions must be constant expressions
    default:

答案 3 :(得分:1)

这样做。

Letter l = Letter.valueOf("A");

Letter l = Enum.valueOf(Letter.class, "A");

switch (l) {
    case A:
    case B:
    case C:
    default:
}

答案 4 :(得分:1)

如果字符串与枚举中的某个常量不匹配,则抛出java.lang.IllegalArgumentException: No enum constant。尝试下一个:

class Letter {
    A, B, C;
    public static Letter fromString(String str) {
    if (str != null) {
      for (Letter l : Letter.values()) {
        if (l.toString().equals(str)) {
            return l;
        }
      }
    }
    return null;
  }
}