让我们假设以下类层次结构:
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
是否可以将相同的通配符绑定(bind)到上限和下限?
我会想象这样的事情:
List<? extends A super B> combined;
List<? extends A & super B> combined;
但是,这些似乎会引发编译时错误。
有没有办法将通用通配符绑定(bind)到类层次结构的特定部分?
我感兴趣这在理论上是否可行,但我没有实际的用例。
最佳答案
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.
对于有界通用通配符,这意味着仅允许一个通配符绑定(bind)。
关于java - 相同通配符的下限和上限通用约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71780217/