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

前端 未结 27 2233
旧巷少年郎
旧巷少年郎 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 > Enum getEnumValue(String what, Class enumClass) {
        Enum unknown=null;
        for (Enum enumVal: enumClass.getEnumConstants()) {  
            if (what.compareToIgnoreCase(enumVal.name()) == 0) {
                return enumVal;
            }
            if (enumVal.name().compareToIgnoreCase("unknown") == 0) {
                unknown=enumVal;
            }
        }  
        return unknown;
    }
    

提交回复
热议问题