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

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

    You may need to this :

    public enum ObjectType {
        PERSON("Person");
    
        public String parameterName;
    
        ObjectType(String parameterName) {
            this.parameterName = parameterName;
        }
    
        public String getParameterName() {
            return this.parameterName;
        }
    
        //From String method will return you the Enum for the provided input string
        public static ObjectType fromString(String parameterName) {
            if (parameterName != null) {
                for (ObjectType objType : ObjectType.values()) {
                    if (parameterName.equalsIgnoreCase(objType.parameterName)) {
                        return objType;
                    }
                }
            }
            return null;
        }
    }
    

    One More Addition :

       public static String fromEnumName(String parameterName) {
            if (parameterName != null) {
                for (DQJ objType : DQJ.values()) {
                    if (parameterName.equalsIgnoreCase(objType.name())) {
                        return objType.parameterName;
                    }
                }
            }
            return null;
        }
    

    This will return you the Value by a Stringified Enum Name For e.g. if you provide "PERSON" in the fromEnumName it'll return you the Value of Enum i.e. "Person"

提交回复
热议问题