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

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

    O(1) method inspired from thrift generated code which utilize a hashmap.

    public enum USER {
            STUDENT("jon",0),TEACHER("tom",1);
    
            private static final Map map = new HashMap<>();
    
            static {
                    for (USER user : EnumSet.allOf(USER.class)) {
                            map.put(user.getTypeName(), user.getIndex());
                    }
            }
    
            public static int findIndexByTypeName(String typeName) {
                    return map.get(typeName);
            }
    
            private USER(String typeName,int index){
                    this.typeName = typeName;
                    this.index = index;
            }
            private String typeName;
            private int index;
            public String getTypeName() {
                    return typeName;
            }
            public void setTypeName(String typeName) {
                    this.typeName = typeName;
            }
            public int getIndex() {
                    return index;
            }
            public void setIndex(int index) {
                    this.index = index;
            }
    
    }
    

提交回复
热议问题