Java Language Get enum constant by name


Example

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() that returns a Guava Optional to eliminate explicit exception handling:

DayOfWeek defaultDay = DayOfWeek.SUNDAY;
DayOfWeek day = Enums.valueOf(DayOfWeek.class, "INVALID").or(defaultDay);
assert day == DayOfWeek.SUNDAY;