-1

我想将字符串转换为枚举。但是怎么做?

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:
}
4

5 回答 5

5

首先Letter必须是一个枚举:

enum Letter {
    A, B, C
}

Letter letter = Letter.valueOf("A")
// and just switch
switch (letter) {
    case A:
    case B:
    case C:
}
于 2013-10-24T13:21:47.647 回答
3

你可以这样做:

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

ideone 上的演示

于 2013-10-24T13:22:05.680 回答
2

首先使该枚举而不是类替换为此

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:
于 2013-10-24T13:24:06.127 回答
1

这样做。

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

或者

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

switch (l) {
    case A:
    case B:
    case C:
    default:
}
于 2013-10-24T13:22:28.733 回答
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;
  }
}
于 2013-10-24T13:28:43.570 回答