Using string representations of enum values in switch-case

Bloke picture Bloke · Apr 30, 2012 · Viewed 25k times · Source

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;

Answer

Peter Lawrey picture Peter Lawrey · Apr 30, 2012

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: