java枚举根据值获取名称,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 enumType = DayOfWeek.class;
DayOfWeek day = Enum.valueOf(enumType, "SUNDAY");
assert day == DayOfWeek.SUNDAY;
如果指定的枚举不具有名称匹配的常量,则这两种valueOf()⽅法都将引发IllegalArgumentException。
Guava库提供了⼀个辅助⽅法,该⽅法返回⼀个Guava以消除显式的异常处理:IfPresent()Optional
DayOfWeek defaultDay = DayOfWeek.SUNDAY;
DayOfWeek day = Enums.valueOf(DayOfWeek.class, "INVALID").or(defaultDay);
assert day == DayOfWeek.SUNDAY;java valueof

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。