Reputation: 2469
Why is it not possible to use enum values as strings in a switch case? (Or what is wrong with this:)
String argument;
switch (argument) {
case MyEnum.VALUE1.toString(): // Isn't this equal to "VALUE1" ?
// something
break;
case MyEnum.VALUE2.toString():
// something else
break;
Upvotes: 24
Views: 46240
Reputation: 1575
To add to the Peter Lawrey's comments, have a look at this post from last year which discusses Switching on String in Java before and after JDK7.
Upvotes: 1
Reputation: 726849
case MyEnum.VALUE1.toString(): // Isn't this equal to "VALUE1" ?
No, not necessarily: you are free to provide your own implementation of toString()
public enum MyType {
VALUE1 {
public String toString() {
return "this is my value one";
}
},
VALUE2 {
public String toString() {
return "this is my value two";
}
}
}
Moreover, someone who is maintaining your code could add this implementation after you leave the company. That is why you should not rely on String values, and stick to using numeric values (as represented by the constants MyEnum.VALUE1
, MyEnum.VALUE2
, etc.) of your enum
s instead.
Upvotes: 7
Reputation: 533680
You can only use strings which are known at compile time. The compiler cannot determine the result of that expression.
Perhaps you can try
String argument = ...
switch(MyEnum.valueOf(argument)) {
case VALUE1:
case VALUE2:
Upvotes: 58