Say we have an enum DayOfWeek
:
enum DayOfWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
An enum is compiled with a built-in static valueOf()
method which can be used to lookup a constant by its name:
String dayName = DayOfWeek.SUNDAY.name();
assert dayName.equals("SUNDAY");
DayOfWeek day = DayOfWeek.valueOf(dayName);
assert day == DayOfWeek.SUNDAY;
This is also possible using a dynamic enum type:
Class<DayOfWeek> enumType = DayOfWeek.class;
DayOfWeek day = Enum.valueOf(enumType, "SUNDAY");
assert day == DayOfWeek.SUNDAY;
Both of these valueOf()
methods will throw an IllegalArgumentException
if the specified enum does not have a constant with a matching name.
The Guava library provides a helper method [Enums.getIfPresent()](<https://google.github.io/guava/releases/18.0/api/docs/com/google/common/base/Enums.html#getIfPresent(java.lang.Class,%20java.lang.String)>)
that returns a Guava [Optional](<https://google.github.io/guava/releases/18.0/api/docs/com/google/common/base/Optional.html>)
to eliminate explicit exception handling:
DayOfWeek defaultDay = DayOfWeek.SUNDAY;
DayOfWeek day = Enums.valueOf(DayOfWeek.class, "INVALID").or(defaultDay);
assert day == DayOfWeek.SUNDAY;