Using string representations of enum values in switch-case

case, enums, java, switch-statement, tostring

Solution

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:

Problem

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; ```

Original source

Related problems