Java nonconstant expressions in switch statements

enums, java

Solution

Add a static method that accepts the `String id` as a parameter and returns the corresponding `MyEnum`:

public enum MyEnum {
    VALUE1("value.1"),
    VALUE2("value.2");

    private String id;

    private MyEnum(String value) {
        this.id = value;
    }

    public String getId() {
        return id;
    }

    public static MyEnum fromId(String id){
        for(MyEnum e:MyEnum.values()){
            if(e.getId().equals(id)){
                return e;
            }
        }
        throw new RuntimeException("Enum not found");
    }

    public static void main(String[] args) {
        String value = "value.2";
        switch(MyEnum.fromId(value)){
        case VALUE1:
            System.out.println("ID 1");
        break;
        case VALUE2:
            System.out.println("ID 2");
            break;
        }
    }
}

Problem

I have an enum class that looks like the following: ``` public enum MyEnum { VALUE1("value.1"), VALUE2("value.2"); private String value; private MyEnum(String value) { this.value = value; } public String getId() { return id; } } ``` I want to have a switch statement on the values of the enum. Something like the following: ``` switch (myString) { case MyEnum.VALUE1.getId(): ... } ``` I get the following compile time error: case expressions must be constant expressions. Is there any way to get this to work with an enum and switch statement? The reason why I added values to the enum is because I want some IDs with "." and other nonallowed characters.

Original source

Related problems