Wednesday, August 14, 2013

Java: Converting String to Enum

Sometimes is necessary to convert a String value to an Enum, perhaps because we have the value as a String in the database, but we want to manipulate it as an Enumerator in the Java code.

The follow code shows hot to obtain the Enum value from a String. Basically, a static method is added to the Enum to return the specif Enum value. This is accomplished by iterating all the Enum values and making a comparison with the String value passed as a parameter. If the String does not match with any of the values, then an illegal argument exception is thrown.

public enum Volcano {

 IRAZU("Irazu"), POAS("Poas"), ARENAL("Arenal"), RINCON_DE_LA_VIEJA("Rincon de la vieja");

 private String name;

 private Volcano(String name) { = name;

 public static Volcano fromString(String name) {
  if (name == null) {
   throw new IllegalArgumentException();
  for (Volcano volcano : values()) {
   if (name.equalsIgnoreCase(volcano.getName())) {
    return volcano;
  // Passed string value does not correspond to a valid enum value.
  throw new IllegalArgumentException();

 public String getName() {

 public static void main(String[] args) {
  Volcano volcano1 = Volcano.fromString("Poas");

  Volcano volcano2 = Volcano.fromString("rincon de la vieja");

  Volcano volcano3 = Volcano.fromString("Fuji");


 at com.bodybuilding.common.enums.Volcano.fromString(
 at com.bodybuilding.common.enums.Volcano.main(

No comments:

Post a Comment