如何将嵌套枚举与 Java 类型擦除结合使用
public enum Days {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
public enum WeekDays{
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
}
public enum WeekEnds{
SATURDAY,
SUNDAY;
}
}
public class InnerEnumTestClass<E extends Enum<E>> {
public E enumtype;
/**
* @param enumtype
*/
public InnerEnumTestClass(E enumtype) {
super();
this.enumtype = enumtype;
}
/**
* @param args
*/
public static void main(String[] args) {
InnerEnumTestClass<Days> testObj =
new InnerEnumTestClass<Days>(Days.WeekDays.MONDAY);
// I get the following compiler error.
//The constructor InnerEnumTestClass<Days>(Days.WeekDays) is undefined
}
}
正如您所看到的,InnerEnumTestClass 类仅接受类型,但我需要构造函数来接受 Days、Days.WeekDays 和 Days.Weekends。
如何建立这个?
public enum Days {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
public enum WeekDays{
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
}
public enum WeekEnds{
SATURDAY,
SUNDAY;
}
}
public class InnerEnumTestClass<E extends Enum<E>> {
public E enumtype;
/**
* @param enumtype
*/
public InnerEnumTestClass(E enumtype) {
super();
this.enumtype = enumtype;
}
/**
* @param args
*/
public static void main(String[] args) {
InnerEnumTestClass<Days> testObj =
new InnerEnumTestClass<Days>(Days.WeekDays.MONDAY);
// I get the following compiler error.
//The constructor InnerEnumTestClass<Days>(Days.WeekDays) is undefined
}
}
As you see the Class InnerEnumTestClass accepts only type but I need the constructor to accept Days, Days.WeekDays and Days.Weekends.
How to establish this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你不想这样做。你的类型太过分了。 Days.MONDAY 与 Days.Weekdays.MONDAY 等属于不同类型。如果它们不可比较,那么同时拥有它们就没有多大意义。我认为你应该有一组用于日期名称的枚举常量和一个
EnumSet。 WeekendDays = EnumSet.of(Days.SATURDAY, Days.SUNDAY)
。 WeekendDays 中缺少日期名称 =>这是一个工作日。I don't think you want to do this. You're overdoing the types. Days.MONDAY is of a different type to Days.Weekdays.MONDAY , etc. There's not much point in having them both if they're not commensurable. I think you should have one set of enum constants for the day names and an
EnumSet<Days> WeekendDays = EnumSet.of(Days.SATURDAY, Days.SUNDAY)
. Absence of a day name from WeekendDays => it is a weekday.仅修复您遇到的错误。将 main 中的声明更正为
Only fixing the error that you have. Correct the declartion in your main to