【发布时间】:2021-08-13 17:51:19
【问题描述】:
免责声明:泛型不是很强大。
假设我有这样的枚举:
public enum FirstEnum implements BaseEnum<FirstEnum> {
SOMETHING_1(Month.FEBRUARY, MZ_AUGUST, MZ_NOVEMBER),
SOMETHING_2(Month.JANUARY, MZ_APRIL, MZ_NOVEMBER);
private final Month month;
private final List<OtherEnum> otherEnumList;
FirstEnum(final Month month, final OtherEnum... otherEnumList) {
this.month = month;
this.otherEnumList = Arrays.asList(otherEnumList);
}
public static List<OtherEnum> getByMonth(final Month month) {
for (final FirstEnum firstEnum : FirstEnum.values()) {
if (month.equals(firstEnum.getMonth())) {
return firstEnum.getOtherEnumList();
}
}
return Collections.emptyList();
}
}
还有一个像这样的 SecondEnum,但现在不相关。 我的问题是如何实现 BaseEnum(我认为它是一个接口),其中 getByMonth() 方法将使用泛型实现。
我正在尝试这样的事情(但它根本不起作用):
public interface BaseEnum<T extends BaseEnum<T>> {
static List<OtherEnum> getByMonth(final Month month) {
for (final T firstEnum : T.values()) {
if (month.equals(firstEnum.getMonth())) {
return Arrays.asList(firstEnum.getOtherEnumList());
}
}
return Collections.emptyList();
}
}
感谢任何帮助!
【问题讨论】: