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) { 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