实现采用枚举的接口的类
因此,假设我有一个简单的枚举和一个使用它的类:
enum ThingType { POTATO, BICYCLE };
class Thing {
public void setValueType(ThingType value) { ... }
public ThingType getValueType() { ... }
}
但是,实际上,我有很多实现 setValueType 的不同类,每个类都有不同类型的枚举。 我想创建一个这些类可以实现的接口,该接口支持使用泛型的 setValueType 和 getValueType:
interface ValueTypeable {
public Enum<?> getValueType(); // This works
public <T extends Enum<T>> setValueType(T value); // this fails horribly
}
我无法更改类模型,因为这些类是从 XML 模式 (JAXB) 自动生成的。 我觉得我没有掌握枚举和泛型的结合。 这里的目标是我希望能够允许用户从枚举列表中进行选择(因为我在运行时已经知道类型)并在特定类中设置值。
谢谢!
So, say I have a simple enum and a class that uses it:
enum ThingType { POTATO, BICYCLE };
class Thing {
public void setValueType(ThingType value) { ... }
public ThingType getValueType() { ... }
}
But, in reality, I have lots of different classes that implement setValueType, each with a different kind of enum. I want to make an interface that these classes can implement that supports setValueType and getValueType using generics:
interface ValueTypeable {
public Enum<?> getValueType(); // This works
public <T extends Enum<T>> setValueType(T value); // this fails horribly
}
I can't change the class model because the classes are auto-generated from an XML schema (JAXB). I feel like I'm not grasping enums and generics combined. The goal here is that I want to be able to allow a user to select from a list of enums (as I already know the type at runtime) and set the value in a particular class.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过参数化接口本身。 就像:
然后你让子类扩展具有正确类型的子类:
Have you tried parameterizing the interface itself. Like:
Then you have the subclass extend the one with right type:
枚举适用于拥有一组固定的枚举。 当您说每个实现都有自己的实现时,那么您就不再拥有固定的集合,并且您尝试使用枚举的方式也不符合您的需求。
您可能对 Java 能够拥有抽象枚举的请求感兴趣。
enums are for when you have a fixed set of them. When you say that each implementation has its own, then you no longer have a fixed set, and how you are trying to use enums doesn't match your needs.
You might be interested in the request for Java to be able to have abstract enums.