Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java nonconstant expressions in switch statements

Tags:

java

enums

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.

like image 336
allenwoot Avatar asked Feb 18 '26 10:02

allenwoot


1 Answers

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;
        }
    }
}
like image 129
Kevin Bowersox Avatar answered Feb 20 '26 22:02

Kevin Bowersox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!