Organizational Research By

Surprising Reserch Topic

Convert a String to an enum in Java



asked May 15, 2015 in Core java by rajesh
0 votes
13 views



Related Hot Questions

4 Answers

0 votes
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.
answered May 15, 2015 by rajesh
0 votes
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;
  }
}
answered May 15, 2015 by rajesh
0 votes
Here's a nifty utility I use:

/**
 * A common method for all enums since they can't have another base class
 * @param Enum type
 * @param c enum type. All enums must be all caps.
 * @param string case insensitive
 * @return corresponding enum, or null
 */
public static > T getEnumFromString(Class 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.
answered May 15, 2015 by rajesh
0 votes
Here's a method that can do it for any Enum, and is case insensitive.

/**
 * Finds the value of the given enumeration by name, case-insensitive.
 * Throws an IllegalArgumentException if no match is found.  
 **/
public static > T valueOfIgnoreCase(
        Class enumeration, String name) {

    for (T enumValue : enumeration.getEnumConstants()) {
        if (enumValue.name().equalsIgnoreCase(name)) {
            return enumValue;
        }
    }

    throw new IllegalArgumentException(String.format(
        "There is no value with name '%s' in Enum %s",
        name, enumeration.getName()
    ));
}
answered May 15, 2015 by rajesh

...