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

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

    To add to the previous answers, and address some of the discussions around nulls and NPE I'm using Guava Optionals to handle absent/invalid cases. This works great for URI/parameter parsing.

    public enum E {
        A,B,C;
        public static Optional fromString(String s) {
            try {
                return Optional.of(E.valueOf(s.toUpperCase()));
            } catch (IllegalArgumentException|NullPointerException e) {
                return Optional.absent();
            }
        }
    }
    

    For those not aware, here's some more info on avoiding null with Optional: https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional

提交回复
热议问题