[英]Java Bounded Type Parameter in Enum
I am trying to create following enum. 我正在尝试创建以下枚举。
public enum MyEnum{
LEAD {
@Override
public boolean isValid(Lead lead) { //compile error, asks to retain type as T
}
},
TASK {
@Override
public boolean isValid(Task task) { //compile error, asks to retain type as T
}
};
public abstract <T extends SObject> boolean isValid(T object);
}
Lead
and Task
classes both extend SObject
. Lead
和Task
类都扩展了SObject
。 My intention is to basically let clients be able to use MyEnum.LEAD.isValid(lead)
or MyEnum.TASK.isValid(task)
. 我的意图是基本上让客户能够使用
MyEnum.LEAD.isValid(lead)
或MyEnum.TASK.isValid(task)
。 Compiler shouldn't allow to pass other types. 编译器不应允许传递其他类型。
Could someone help in understand why this is happening. 有人可以帮助理解为什么会这样。
Thanks 谢谢
You need to override the generic method with the same generic method. 您需要使用相同的泛型方法覆盖泛型方法。 If you want to do what you are asking you need a generic class - which an
enum
cannot be. 如果你想做你想要的,你需要一个泛型类 -
enum
不可能。
The point being that I refer to the enum
by the class reference - ie 关键是我通过类引用引用
enum
- 即
final MyEnum myenum = MyEnum.LEAD;
Now if I call myenum.isValid()
I should be able to call it with any SObject
as defined by your abstract
method. 现在,如果我调用
myenum.isValid()
我应该可以使用abstract
方法定义的任何 SObject
来调用它。
The generic method definition that you have doesn't actually do anything. 您拥有的通用方法定义实际上并没有做任何事情。 All it is doing is capturing the type of the passed in
SObject
and storing it as T
. 它所做的就是捕获传入
SObject
的类型并将其存储为T
A generic method is commonly used to tie together types of parameters, for example 例如,通用方法通常用于将参数类型联系在一起
<T> void compare(Collection<T> coll, Comparator<T> comparator);
Here we do not care what T
actually is - all we require is that the Comparator
can compare the things that are in the Collection
. 在这里,我们不关心什么
T
的是-所有我们需要的是, Comparator
可以比较是在的东西Collection
。
What you are thinking of is a generic class, something like: 你在想什么是一个泛型类,如:
interface MyIface<T> {
boolean isValid(T object);
}
And then 接着
class LeadValid implements MyIface<Lead> {
public boolean isValid(Lead object){}
}
You see the difference is that you would have a MyIface<Lead>
- you would have to declare the type of MyIface
. 您会发现不同之处在于您将拥有
MyIface<Lead>
- 您必须声明MyIface
的类型 。 In the enum
case you only have a MyEnum
. 在
enum
情况下,你只有一个MyEnum
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.