Java通过名称获取枚举常量
示例
假设我们有一个枚举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库提供了一个辅助方法,该方法返回一个Guava以消除显式的异常处理:Enums.getIfPresent()Optional
DayOfWeek defaultDay = DayOfWeek.SUNDAY; DayOfWeek day = Enums.valueOf(DayOfWeek.class, "INVALID").or(defaultDay); assert day == DayOfWeek.SUNDAY;