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

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

    In Java 8 the static Map pattern is even easier and is my preffered method. If you want to use the Enum with Jackson you can override toString and use that instead of name, then annotate with @JsonValue

    public enum MyEnum {
        BAR,
        BAZ;
        private static final Map MAP = Stream.of(MyEnum.values()).collect(Collectors.toMap(Enum::name, Function.identity()));
        public static MyEnum fromName(String name){
            return MAP.get(name);
        }
    }
    
    public enum MyEnumForJson {
        BAR("bar"),
        BAZ("baz");
        private static final Map MAP = Stream.of(MyEnumForJson.values()).collect(Collectors.toMap(Object::toString, Function.identity()));
        private final String value;
    
        MyEnumForJson(String value) {
            this.value = value;
        }
    
        @JsonValue
        @Override
        public String toString() {
            return value;
        }
    
        public static MyEnumForJson fromValue(String value){
            return MAP.get(value);
        }
    }
    

提交回复
热议问题