0

I want to transform a String into an enum. But how?

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:
}
membersound
  • 81,582
  • 193
  • 585
  • 1,120

5 Answers5

5

First the Letter must be an enum:

enum Letter {
    A, B, C
}

Letter letter = Letter.valueOf("A")
// and just switch
switch (letter) {
    case A:
    case B:
    case C:
}
René Link
  • 48,224
  • 13
  • 108
  • 140
3

You can do it like this:

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

Demo on ideone.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Make that enum first instead of Class Replace to this

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:
shikjohari
  • 2,278
  • 11
  • 23
1

Do like this.

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

or

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

switch (l) {
    case A:
    case B:
    case C:
    default:
}
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
1

If the string don't match with some constant in the enum, throws an java.lang.IllegalArgumentException: No enum constant. Try with the next:

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;
  }
}
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148