Java枚举类可以通过以下步骤使用:
enum
关键字声明一个枚举类,并在其中定义枚举常量。例如:public enum DayOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
DayOfWeek day = DayOfWeek.MONDAY;
System.out.println(day); // 输出: MONDAY
public enum DayOfWeek {
// ...
public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}
DayOfWeek day = DayOfWeek.SATURDAY;
System.out.println(day.isWeekend()); // 输出: true
public enum DayOfWeek {
// ...
public static DayOfWeek fromString(String dayStr) {
for (DayOfWeek day : DayOfWeek.values()) {
if (day.name().equalsIgnoreCase(dayStr)) {
return day;
}
}
throw new IllegalArgumentException("Invalid day of week: " + dayStr);
}
}
DayOfWeek day = DayOfWeek.fromString("monday");
System.out.println(day); // 输出: MONDAY
这些是使用Java枚举类的基本步骤,可以根据需要进行扩展和定制。