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

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

    My 2 cents here: using Java8 Streams + checking an exact string:

    public enum MyEnum {
        VALUE_1("Super"),
        VALUE_2("Rainbow"),
        VALUE_3("Dash"),
        VALUE_3("Rocks");
    
        private final String value;
    
        MyEnum(String value) {
            this.value = value;
        }
    
        /**
         * @return the Enum representation for the given string.
         * @throws IllegalArgumentException if unknown string.
         */
        public static MyEnum fromString(String s) throws IllegalArgumentException {
            return Arrays.stream(MyEnum.values())
                    .filter(v -> v.value.equals(s))
                    .findFirst()
                    .orElseThrow(() -> new IllegalArgumentException("unknown value: " + s));
        }
    }
    

    ** EDIT **

    Renamed the function to fromString() since naming it using that convention, you'll obtain some benefits from Java language itself; for example:

    1. Direct conversion of types at HeaderParam annotation

提交回复
热议问题