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

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

    Adding on to the top rated answer, with a helpful utility...

    valueOf() throws two different Exceptions in cases where it doesn't like its input.

    • IllegalArgumentException
    • NullPointerExeption

    If your requirements are such that you don't have any guarantee that your String will definitely match an enum value, for example if the String data comes from a database and could contain old version of the enum, then you'll need to handle these often...

    So here's a reusable method I wrote which allows us to define a default Enum to be returned if the String we pass doesn't match.

    private static > T valueOf( String name , T defaultVal) {
            try {
                return Enum.valueOf(defaultVal.getDeclaringClass() , name);
            } catch (IllegalArgumentException | NullPointerException e) {
                return defaultVal;
            }
        }
    

    Use it like this:

    public enum MYTHINGS {
        THINGONE,
        THINGTWO
    }
    
    public static void main(String [] asd) {
      valueOf("THINGTWO" , MYTHINGS.THINGONE);//returns MYTHINGS.THINGTWO
      valueOf("THINGZERO" , MYTHINGS.THINGONE);//returns MYTHINGS.THINGONE
    }
    

提交回复
热议问题