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

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

    I like to use this sort of process to parse commands as strings into enumerations. I normally have one of the enumerations as "unknown" so it helps to have that returned when the others are not found (even on a case insensitive basis) rather than null (that meaning there is no value). Hence I use this approach.

    static <E extends Enum<E>> Enum getEnumValue(String what, Class<E> enumClass) {
        Enum<E> unknown=null;
        for (Enum<E> enumVal: enumClass.getEnumConstants()) {  
            if (what.compareToIgnoreCase(enumVal.name()) == 0) {
                return enumVal;
            }
            if (enumVal.name().compareToIgnoreCase("unknown") == 0) {
                unknown=enumVal;
            }
        }  
        return unknown;
    }
    
    0 讨论(0)
  • 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<String,MyEnum> 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<String,MyEnum> map = new ConcurrentHashMap<String, MyEnum>();
            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

    0 讨论(0)
  • 2020-11-21 11:59

    Apache's commons-lang library has a static function org.apache.commons.lang3.EnumUtils.getEnum which will map a String to your Enum type. Same answer essentially as Geoffreys but why roll your own when it's out there in the wild already.

    0 讨论(0)
提交回复
热议问题