java - 相同通配符的下限和上限通用约束

标签 java generics bounded-wildcard

让我们假设以下类层次结构:

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/

相关文章:

java - 覆盖期间的动态多态性

c# - 为什么具有 T : class result in boxing? 约束的泛型方法

c# - 是否收集了 MakeGenericType/泛型类型的垃圾?

java - 什么是 PECS(生产者扩展消费者 super )?

java - 如何将 Scala List[String] 转换为旧版 Java List<?>

java - 在通配符类型 ArrayList 中添加元素

java - 是否有用于向文件中添加额外信息的任何 Java 注释?

java - 将类传递给 Kotlin 具体化方法

Java:从具有缓冲输入的随机访问文件中读取字符串

c# - 是否可以将 Func<T> 存储在字典中?