How to get an enum value from a string value in Java?

前端 未结 27 2619
旧巷少年郎
旧巷少年郎 2020-11-21 10:53

Say I have an enum which is just

public enum Blah {
    A, B, C, D
}

and I would like to find the enum value of a string, for example

27条回答
  •  滥情空心
    2020-11-21 11:47

    Another way of doing this by using implicit static method name() of Enum. name will return the exact string used to create that enum which can be used to check against provided string:

    public enum Blah {
    
        A, B, C, D;
    
        public static Blah getEnum(String s){
            if(A.name().equals(s)){
                return A;
            }else if(B.name().equals(s)){
                return B;
            }else if(C.name().equals(s)){
                return C;
            }else if (D.name().equals(s)){
                return D;
            }
            throw new IllegalArgumentException("No Enum specified for this string");
        }
    }
    

    Testing:

    System.out.println(Blah.getEnum("B").name());

    //it will print B  B
    

    inspiration: 10 Examples of Enum in Java

提交回复
热议问题