按名稱獲取列舉常量

假設我們有一個 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;