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

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

    Another utility capturing in reverse way. Using a value which identify that Enum, not from its name.

    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    import java.util.EnumSet;
    
    public class EnumUtil {
    
        /**
         * Returns the Enum of type enumType whose a 
         * public method return value of this Enum is 
         * equal to valor.
    * Such method should be unique public, not final and static method * declared in Enum. * In case of more than one method in match those conditions * its first one will be chosen. * * @param enumType * @param value * @return */ public static > E from(Class enumType, Object value) { String methodName = getMethodIdentifier(enumType); return from(enumType, value, methodName); } /** * Returns the Enum of type enumType whose * public method methodName return is * equal to value.
    * * @param enumType * @param value * @param methodName * @return */ public static > E from(Class enumType, Object value, String methodName) { EnumSet enumSet = EnumSet.allOf(enumType); for (E en : enumSet) { try { String invoke = enumType.getMethod(methodName).invoke(en).toString(); if (invoke.equals(value.toString())) { return en; } } catch (Exception e) { return null; } } return null; } private static String getMethodIdentifier(Class enumType) { Method[] methods = enumType.getDeclaredMethods(); String name = null; for (Method method : methods) { int mod = method.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isStatic(mod) && !Modifier.isFinal(mod)) { name = method.getName(); break; } } return name; } }

    Example:

    public enum Foo {
        ONE("eins"), TWO("zwei"), THREE("drei");
    
        private String value;
    
        private Foo(String value) {
            this.value = value;
        }
    
        public String getValue() {
            return value;
        }
    }
    

    EnumUtil.from(Foo.class, "drei") returns Foo.THREE, because it will use getValue to match "drei", which is unique public, not final and not static method in Foo. In case Foo has more than on public, not final and not static method, for example, getTranslate which returns "drei", the other method can be used: EnumUtil.from(Foo.class, "drei", "getTranslate").

提交回复
热议问题