How to use ENUM with SWITCH, for String based comparison

pjj :

I have a Enum class as below.

public enum TestEnum {
    TEST1("test1"), TEST2("test2");

    private String name;
    TestEnum(String name) {
        this.name= name;
    }
    public String getName(){
        return name;
    }
}

I am trying to use it in SWITCH statement to compare against a String, but not able to use. See below screenshot, I only see .class option. And I am so much surprised because in one other box I can see the values.

enter image description here

Now, another issue I have is that lets say once I see values, I want to do case TestEnum.TEST1.getName(): so that it can work with the switch statement, but here I get error saying that only constants are allowed for switch case.

Could someone please help on this. Basically, what I want that instead of checking a string against number of possible strings like "test1" or "test2" I want to do this using SWITCH.

As an aside, I have 32 IF-ELSEIF blocks, someone told me that I should use SWTICH instead, is it bad is I use 32 IF-ELSEIF blocks.

Maurice Perry :

Case labels are constants. Consider adding a static method in the enum class:

public enum TestEnum {
    TEST1("test1"), TEST2("test2");

    private String name;
    TestEnum(String name) {
        this.name= name;
    }
    public String getName(){
        return name;
    }
    public static TestEnum fromName(String name) {
        for (TestEnum e: values()) {
            if (e.name.equals(name)) {
                return e;
            }
        }
        throw new IllegalArgumentException("Name not found: " + name);
    }
}

You will then be able to write a switch statement:

switch (TestEnum.fromName(name)) {
case TEST1:
    //...
    break;
case TEST2:
    //...
    break;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147855&siteId=1