Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch String with Enum variables

I have got an Enum with different values and want to switch a string variable. Now I hit a wall trying to convert the Enum values to Strings, that I can use as case constant.

My best try was to convert the Enum to a String array, but the switch doesn't seem to accept array values as a case constant. (IntelliJ says: "constant expression required")

Enum myEnum = {FOO, BAR}

String input = "foo"

final String[] constant = Arrays.stream(myEnum.values()).map(Enum::name).toArray(String[]::new); 
//converts Enum to String[]; made it final, so it is "constant" 

       switch (input) {
                    case constant[0]:
                        System.out.println("foo");
                        break;
                    case constant[1]:
                        System.out.println("bar");
                        break;
                     }

Is there an elegant way to make this switch depend on the Enum?

like image 532
Jonas Kautz Avatar asked Jun 11 '26 07:06

Jonas Kautz


1 Answers

You shouldn't convert it because it isn't needed. Also, your code won't even compile because case is a reserved keyword in Java.

You should take a look at the valueOf method of an Enum.

Your code can look like that:

public enum MyEnum {FOO, BAR}

//method
String input = "foo";
MyEnum niceFound = MyEnum.valueOf(input.toUpperCase());

That will return FOO but can throw an IllegalArgumentException when the given value isn't present as type.

like image 168
CodeMatrix Avatar answered Jun 13 '26 19:06

CodeMatrix