每種枚舉有一個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) {
...
}
你可以找到關於使用枚舉here反思工作的一些細節。
只需製作一個「HasNext」界面或其他東西,不是嗎? –