[英]Java: How to Set Bounds on Class Type Field in Enum
I have an enum which has a property that is another class. 我有一个枚举,它具有另一个类的属性。 I want to somewhere put a constraint that all instances of the enum have should have a value for that property that extend a certain upper bound, in this case an interface.
我想在某个地方施加一个约束,即该枚举的所有实例都应具有该属性的值,该值可以扩展某个上限,在这种情况下为接口。 Here is the basic working example without the bound:
这是不受限制的基本工作示例:
public enum MyClassRegistry
{
MyClass(1,com.example.MyClass.class)
private int typeId;
private Class theClass;
}
What I want to do next is something like: 我接下来要做的是:
public enum MyClassRegistry
{
MyClass(1,com.example.MyClass.class)
private int typeId;
private Class<T extends SomeInterface> theClass;
}
To enforce that all values of this field extend a certain upper bound. 为了强制此字段的所有值扩展一定的上限。 Is this possible?
这可能吗? If so, what is the syntax for this?
如果是这样,其语法是什么?
public enum MyClassRegistry
{
MyClass(1,com.example.MyClass);
private int typeId;
private Class<? extends SomeInterface> theClass;
MyClassRegistry(int typeId, Class<? extends SomeInterface> theClass) {
this.typeId = typeId;
this.theClass = theClass;
}
}
An enum
type cannot declare any generic type parameters. enum
类型不能声明任何泛型类型参数。
If you mean you want to have a field that has a type of some super type, an interface for example, simply declare the field as having that type. 如果您要具有一个具有某种超级类型的类型的字段(例如接口),则只需声明该字段具有该类型。
public enum MyClassRegistry
{
First(1, new InterfaceFirstImpl()),
Second(2, new InterfaceSecondImpl()) ;
MyClassRegistry (int id, Interface value) {
this.typeId = id;
this.value = value;
}
private int typeId;
private Interface value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.