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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public enum Volcano {
 
 IRAZU("Irazu"), POAS("Poas"), ARENAL("Arenal"), RINCON_DE_LA_VIEJA("Rincon de la vieja");
 
 private String name;
 
 private Volcano(String name) {
  this.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() {
  return this.name;
 }
 
 public static void main(String[] args) {
  Volcano volcano1 = Volcano.fromString("Poas");
  System.out.println(volcano1);
 
  Volcano volcano2 = Volcano.fromString("rincon de la vieja");
  System.out.println(volcano2);
 
  Volcano volcano3 = Volcano.fromString("Fuji");
 }
}

Output:


POAS
RINCON_DE_LA_VIEJA
java.lang.IllegalArgumentException
 at com.bodybuilding.common.enums.Volcano.fromString(Volcano.java:22)
 at com.bodybuilding.common.enums.Volcano.main(Volcano.java:36)

No comments:

Post a Comment