我想将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:
}
答案 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:
}
答案 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;
}
}