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

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

    Use the pattern from Joshua Bloch, Effective Java:

    (simplified for brevity)

    enum MyEnum {
        ENUM_1("A"),
        ENUM_2("B");
    
        private String name;
    
        private static final Map ENUM_MAP;
    
        MyEnum (String name) {
            this.name = name;
        }
    
        public String getName() {
            return this.name;
        }
    
        // Build an immutable map of String name to enum pairs.
        // Any Map impl can be used.
    
        static {
            Map map = new ConcurrentHashMap();
            for (MyEnum instance : MyEnum.values()) {
                map.put(instance.getName(),instance);
            }
            ENUM_MAP = Collections.unmodifiableMap(map);
        }
    
        public static MyEnum get (String name) {
            return ENUM_MAP.get(name);
        }
    }
    

    Also see:

    Oracle Java Example using Enum and Map of instances

    Execution order of of static blocks in an Enum type

    How can I lookup a Java enum from its String value

提交回复
热议问题