How to match and switch Strings against enums?
本问题已经有最佳答案,请猛点这里访问。
我想将字符串转换为枚举。但是如何呢?
1 2 3 4 5 6 7 8 9 10 11 | 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: } |
首先,
1 2 3 4 5 6 7 8 9 10 11 | enum Letter { A, B, C } Letter letter = Letter.valueOf("A") // and just switch switch (letter) { case A: case B: case C: } |
你可以这样做:
1 2 3 4 5 6 7 | String letter ="A"; switch (Letter.valueOf(letter)) { case A: // No problem! case B: case C: default: } |
IDENO演示。
首先生成枚举而不是类替换为此
1 2 3 4 5 6 | 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: |
如果字符串与枚举中的某个常量不匹配,则抛出一个
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } } |
这样做。
1 | Letter l = Letter.valueOf("A"); |
或
1 2 3 4 5 6 7 8 | Letter l = Enum.valueOf(Letter.class,"A"); switch (l) { case A: case B: case C: default: } |