同一通配符的下限和上限通用约束
Lower and upper bound generic constraints on same wildcard
让我们假设以下 class 层次结构:
class A{}
class B extends A{}
class C extends B{}
class D extends C{}
在Java中,可以像这样用泛型定义通配符:
List<? extends A> aOrDown;//A or any subtype of A
List<? super D> dOrUp;//D or any supertype of D
是否可以将同一个通配符同时绑定到上限和下限?
我会想象这样的事情:
List<? extends A super B> combined;
List<? extends A & super B> combined;
但是,这些似乎会引发编译时错误。
有没有办法将通用通配符绑定到 class 层次结构的特定部分?
我很感兴趣这在理论上是否可行,我没有这方面的实际用例。
Section 4.5.1 of the JLS 指定通用通配符的语法:
TypeArguments:
< TypeArgumentList >
TypeArgumentList:
TypeArgument {, TypeArgument}
TypeArgument:
ReferenceType
Wildcard
Wildcard:
{Annotation} ? [WildcardBounds]
WildcardBounds:
extends ReferenceType
super ReferenceType
这里,WildcardBounds
写在方括号里。在Section 2.4 of the JLS中说明,在此上下文中,方括号表示可选元素只能放一次:
The syntax [x] on the right-hand side of a production denotes zero or one occurrences of x. That is, x is an optional symbol. The alternative which contains the optional symbol actually defines two alternatives: one that omits the optional symbol and one that includes it.
对于有界通用通配符,这意味着只允许一个通配符绑定。
让我们假设以下 class 层次结构:
class A{}
class B extends A{}
class C extends B{}
class D extends C{}
在Java中,可以像这样用泛型定义通配符:
List<? extends A> aOrDown;//A or any subtype of A
List<? super D> dOrUp;//D or any supertype of D
是否可以将同一个通配符同时绑定到上限和下限?
我会想象这样的事情:
List<? extends A super B> combined;
List<? extends A & super B> combined;
但是,这些似乎会引发编译时错误。
有没有办法将通用通配符绑定到 class 层次结构的特定部分?
我很感兴趣这在理论上是否可行,我没有这方面的实际用例。
Section 4.5.1 of the JLS 指定通用通配符的语法:
TypeArguments: < TypeArgumentList > TypeArgumentList: TypeArgument {, TypeArgument} TypeArgument: ReferenceType Wildcard Wildcard: {Annotation} ? [WildcardBounds] WildcardBounds: extends ReferenceType super ReferenceType
这里,WildcardBounds
写在方括号里。在Section 2.4 of the JLS中说明,在此上下文中,方括号表示可选元素只能放一次:
The syntax [x] on the right-hand side of a production denotes zero or one occurrences of x. That is, x is an optional symbol. The alternative which contains the optional symbol actually defines two alternatives: one that omits the optional symbol and one that includes it.
对于有界通用通配符,这意味着只允许一个通配符绑定。