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

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

    Here's a nifty utility I use:

    /**
     * A common method for all enums since they can't have another base class
     * @param  Enum type
     * @param c enum type. All enums must be all caps.
     * @param string case insensitive
     * @return corresponding enum, or null
     */
    public static > T getEnumFromString(Class c, String string) {
        if( c != null && string != null ) {
            try {
                return Enum.valueOf(c, string.trim().toUpperCase());
            } catch(IllegalArgumentException ex) {
            }
        }
        return null;
    }
    

    Then in my enum class I usually have this to save some typing:

    public static MyEnum fromString(String name) {
        return getEnumFromString(MyEnum.class, name);
    }
    

    If your enums are not all caps, just change the Enum.valueOf line.

    Too bad I can't use T.class for Enum.valueOf as T is erased.

提交回复
热议问题