Reputation: 1163
I want to use the following enum as reference in a switch case:
public final enum myEnum {
VALUE1,
VALUE2,
VALUE2,
...
}
I searched the internet already quite some time, but found only examples where the enum is used in the switch statement and the case stament as argument. I want to use only the values of the enum as argument of the case statements, the switch argument is another variable. Something like this:
String otherVariable = "VALUE2";
switch (otherVariable) {
case myEnum,VALUE1.toString():
...
break;
case myEnum,VALUE2.toString():
...
break;
default:
...
break;
When I code this straight forward, I get an error "case expressions must be constant expressions". What am I doing wrong? How do I implement this?
Kind regards WolfiG
Upvotes: 1
Views: 618
Reputation: 14999
What you want is probably
String other = "VALUE2";
MyEnum myEnum = MyEnum.valueOf(other);
switch (myEnum) {
case VALUE1:
...
case VALUE2:
...
}
You can't use myEnum.toString()
because it's a method call, which can create different results between calls (ie non-constant).
Upvotes: 6