![](/img/trans.png)
[英]Is it possible to specify both upper and lower bound constraints on type parameters in Java?
[英]Can you define a generic bound that both has lower and upper bounds?
是否可以定义一个通用绑定:
SomeInterface
MyClass
类的超类 就像是:
Collection<? extends SomeInterface & super MyClass> c; // doesn't compile
根据规范 ,答案是否定的(你可以有super
或extends
,但不是两者):
TypeArguments:\n <TypeArgumentList>\n\n TypeArgumentList: \n TypeArgument\n TypeArgumentList,TypeArgument\n\n TypeArgument:\n 引用类型\n 通配符\n\n 通配符:\n ? WildcardBounds 选择\n\n WildcardBounds:\n 扩展ReferenceType\n 超级ReferenceType
在声明变量时,不能使用带有边界的泛型类型(在您的情况下为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
>
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.