按名称获取枚举常量
假设我们有一个 enum DayOfWeek
:
enum DayOfWeek {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
枚举是使用内置的静态 valueOf()
方法编译的,该方法可用于通过名称查找常量:
String dayName = DayOfWeek.SUNDAY.name();
assert dayName.equals("SUNDAY");
DayOfWeek day = DayOfWeek.valueOf(dayName);
assert day == DayOfWeek.SUNDAY;
使用动态枚举类型也可以这样做:
Class<DayOfWeek> enumType = DayOfWeek.class;
DayOfWeek day = Enum.valueOf(enumType, "SUNDAY");
assert day == DayOfWeek.SUNDAY;
如果指定的枚举没有具有匹配名称的常量,则这两个 valueOf()
方法都将抛出 IllegalArgumentException
。
Guava 库提供了一个帮助方法 Enums.getIfPresent()
,它返回一个 Guava Optional
来消除显式的异常处理:
DayOfWeek defaultDay = DayOfWeek.SUNDAY;
DayOfWeek day = Enums.valueOf(DayOfWeek.class, "INVALID").or(defaultDay);
assert day == DayOfWeek.SUNDAY;