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

前端 未结 27 2166
旧巷少年郎
旧巷少年郎 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:56

    Another solution if the text is not the same to the enumeration value:

    public enum Blah {
        A("text1"),
        B("text2"),
        C("text3"),
        D("text4");
    
        private String text;
    
        Blah(String text) {
            this.text = text;
        }
    
        public String getText() {
            return this.text;
        }
    
        public static Blah fromString(String text) {
            for (Blah b : Blah.values()) {
                if (b.text.equalsIgnoreCase(text)) {
                    return b;
                }
            }
            return null;
        }
    }
    

提交回复
热议问题