Wednesday, May 30, 2012

Java - Convert String to enum


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 of for example "A" which would be Blah.A . How would it be possible to do this?



Is the Enum.ValueOf() the method I need? If so, how would I use this?


Source: Tips4all

9 comments:

  1. Yes, Blah.valueOf("A") will give you Blah.A.

    The static methods valueOf() and values() are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType shows both methods.

    ReplyDelete
  2. Another solution if the text is not the same to the enumeration value:

    public enum Blah {
    A("text1"),
    B("text2"),
    C("text3"),
    D("text4");

    private String text;

    Blah(String text) {
    this.text = text;
    }

    public String getText() {
    return this.text;
    }

    public static Blah fromString(String text) {
    if (text != null) {
    for (Blah b : Blah.values()) {
    if (text.equalsIgnoreCase(b.text)) {
    return b;
    }
    }
    }
    return null;
    }
    }

    ReplyDelete
  3. Here's a nifty utility I use:

    /**
    * A common method for all enums since they can't have another base class
    * @param <T> Enum type
    * @param c enum type. All enums must be all caps.
    * @param string case insensitive
    * @return corresponding enum, or null
    */
    public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string)
    {
    if( c != null && string != null )
    {
    try
    {
    return Enum.valueOf(c, string.trim().toUpperCase());
    }
    catch(IllegalArgumentException ex)
    {
    }
    }
    return null;
    }


    Then in my enum class I usually have this to save some typing:

    public static MyEnum fromString(String name)
    {
    return getEnumFromString(MyEnum.class, name);
    }


    If your enums are not all caps, just change the Enum.valueOf line.

    Too bad I can't use T.class for Enum.valueOf as T is erased.

    ReplyDelete
  4. You should also be careful with your case. Let me explain: doing Blah.valueOf("A") works, but Blah.valueOf("a") will not work. Then again Blah.valueOf("a".toUpperCase()) would work.

    ReplyDelete
  5. Using Blah.valueOf(string) is best but you can use Enum.valueOf(Blah.class, string) as well.

    ReplyDelete
  6. Another way of doing this by using implicit static method name() of Enum. name will return the exact string used to create that enum which can be used to check against provided string:

    public enum Blah {

    A, B, C, D;

    public static Blah getEnum(String s){
    if(A.name().equals(s)){
    return A;
    }else if(B.name().equals(s)){
    return B;
    }else if(C.name().equals(s)){
    return C;
    }else if (D.name().equals(s)){
    return D;
    }
    throw new IllegalArgumentException("No Enum specified for this string");
    }
    }


    Testing:

    System.out.println(Blah.getEnum("B").name());

    //it will print B B


    inspiration: 10 Examples of Enum in Java

    ReplyDelete
  7. public static <T extends Enum<T>> T valueOfIgnoreCase(Class<T> enumeration, String name) {
    for(T enumValue : enumeration.getEnumConstants()) {
    if(enumValue.name().equalsIgnoreCase(name)) {
    return enumValue;
    }
    }
    throw new IllegalArgumentException("There is no value with name '" + name + " in Enum " + enumeration.getClass().getName());
    }

    ReplyDelete
  8. public static MyEnum getFromValue(String value){
    MyEnum resp = null;
    MyEnum nodes[] = values();
    for(int i=0;i<nodes.length;i++){
    if(nodes[i].value.equals(value)){
    resp = nodes[i];
    break;
    }
    }
    return resp;

    ReplyDelete
  9. Here's a method that can do it for any Enum, and is case insensitive. Does anyone know how to get rid of the warning in the return statement?

    /**
    * Finds the value of the given enumeration by name, case-insensitive.
    * Throws an IllegalArgumentException if no match is found.
    **/
    public static <T extends Enum<T>> T valueOfIgnoreCase(Class<T> enumeration, String name) {
    for(Enum enumValue : enumeration.getEnumConstants()) {
    if(enumValue.name().equalsIgnoreCase(name)) {
    return (T) enumValue;
    }
    }
    throw new IllegalArgumentException("There is no value with name '" + name + " in Enum " + enumeration.getClass().getName());
    }

    ReplyDelete