是否可以定义一个通用界限:
- 实现一个接口
SomeInterface - 是某个类的超类
MyClass
就像是:
Collection<? extends SomeInterface & super MyClass> c; // doesn't compile
根据spec,答案是否定的(你可以拥有superor extends,但不能同时拥有):
类型参数:
< 类型参数列表 >
类型参数列表:
类型参数
类型参数列表,类型参数
类型参数:
参考类型
通配符
通配符:
? 通配符边界选择
通配符边界:
扩展参考类型
超级参考类型
T声明变量时,您不能将泛型类型(在您的情况下)与边界一起使用。
它应该是通配符 ( ?),或者只使用类的完整泛型类型。
例如
// Here only extends is allowed
class My< T extends SomeInterface >
{
// If using T, then no bounds are allowed
private Collection<T> var1;
private Collection< ? extends SomeInterface > var2;
// Cannot have extends and super on the same wildcard declaration
private Collection< ? super MyClass > var3;
// You can use T as a bound for wildcard
private Collection< ? super T > var4;
private Collection< ? extends T > var5;
}
在某些情况下,您可以通过向类(或方法)添加额外的泛型参数并在该特定参数上添加绑定来收紧声明:
class My <
T extends MyClass< I >,
I extends SomeInterface
>
{
}