Using string representations of enum values ​​in a switch case

Why is it impossible to use enum values ​​as strings in the case of a switch? (Or what's wrong with that :)

String argument; switch (argument) { case MyEnum.VALUE1.toString(): // Isn't this equal to "VALUE1" ? // something break; case MyEnum.VALUE2.toString(): // something else break; 
+8
java tostring enums switch-statement case
source share
4 answers

You can only use strings that are known at compile time. The compiler cannot determine the result of this expression.

Maybe you can try

 String argument = ... switch(MyEnum.valueOf(argument)) { case VALUE1: case VALUE2: 
+22
source share

case MyEnum.VALUE1.toString (): // Isn't that equal to "VALUE1"?

No, optional: you can 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"; } } 

}

In addition, someone who supports your code may add this implementation after leaving the company. This is why you should not rely on String values ​​and adhere to the use of numeric values ​​(as represented by the constants MyEnum.VALUE1 , MyEnum.VALUE2 , etc.) of your enum .

+5
source share

To add to Peter Lowry’s comments, check out this last year article that discusses the inclusion of String in Java before and after JDK7.

+1
source share

EDIT . Sorry for the C # answer to the Java question. I don’t know what went wrong.

You can use string values ​​(including the string values ​​of the enumerations). However, you can use compile-time constants. You call the ToString() method, which must be evaluated at runtime.

With C # 6, you can use this persistent alternative: case nameof(SomeEnum.SomeValue):

Nameof () is evaluated at compile time, just for a string that matches the (unskilled) name of a given variable, type, or member. Its value corresponds to the value of SomeEnum.ToString() .

-one
source share

All Articles