每个枚举都有一个ordinal
,因此获取所有枚举的“下一个”值是有效的 - 而不仅仅是那些您尝试使用基类的枚举。这意味着您可以编写以下辅助方法:
public static <T extends Enum<T>> T getNext(T current) {
Class<T> enumType = current.getDeclaringClass();
T[] enumConstants = enumType.getEnumConstants(); // Similar to e.g. Day.values()
int currentOrdinal = current.ordinal();
int nextOrdinal = currentOrdinal + 1;
if (nextOrdinal == enumConstants.length) { // Handle wrapping around to the beginning of the enum values
nextOrdinal = 0;
}
return enumConstants[nextOrdinal];
}
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public enum Month {
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
}
public static void main(String... args) {
System.out.println(getNext(Day.MONDAY)); // TUESDAY
System.out.println(getNext(Day.SUNDAY)); // MONDAY
System.out.println(getNext(Month.JANUARY)); // FEBRUARY
System.out.println(getNext(Month.DECEMBER)); // JANUARY
}
如果您真的不想对所有枚举执行此操作(也许对于未严格排序的枚举没有意义),那么您可以应用标记接口,如下所示:
public interface Ordered {}
public enum Day implements Ordered {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public static <T extends Enum<T> & Ordered> T getNext(T current) {
...
}
您可以在此处找到有关反思性使用枚举的更多详细信息。