如何在 Java 中理解有界通配符?

How to grok bounded wildcards in Java?

wikipedia article about co- and contravariance 中有一个示例用例,然后是描述类型声明含义的解释性句子。我发现这非常有用。看了几遍解释,感觉自己看懂了。

<T extends Comparable<? super T>> T max(Collection<T> coll);

The bounded wildcard ? super T conveys the information that max calls only contravariant methods from the Comparable interface.

有人可以用类似的语言解释一下 java.util.function.Consumer @FunctionalInterfaceandThen() 函数的类型声明是什么意思:

public interface Consumer<T> {
    void accept(T t);
    default Consumer<T> andThen(Consumer<? super T> after) {

例如

The bounded wildcard ? super T conveys the information that andThen .... ?


我还有一个次要问题:我怎样才能发现自己,这样的类型声明意味着什么?例如。在上面的第一个示例中,来自 java.util.Collections util class:class - T 的类型边界如何能够传达有关 T 的方法正在做什么的信息?任何人都可以指出 Java 语言规范中的相关段落吗?

第一个问题的可能答案:

public interface Consumer<T> {
    void accept(T t);
    default Consumer<T> andThen(Consumer<? super T> after) {

The bounded wildcard ? super T conveys the information that andThen takes Consumers of T or supertypes of T, aka. contravariant Consumers, as arguments.


次要问题的可能答案:

基本上 - 完全独立于泛型 (!) - Java 语言中的 method return return types are inherently "covariant"(假定为 "producers")。如果覆盖子 class 中的方法,您始终可以声明更具体的 return 类型。

方法参数当然也是 "covariant" - 您只能传递比方法签名指定的更具体的对象。但是在 subclasses 上,虽然该方法在技术上是 not overriden for non-parametric arguments - adhering to the Liskov_substitution_principle - it often makes sense to declare "contravariant" argument types in child classes, which - if the name and other arguments are equal - "overloads" the methods in the parent class. "Static" (reference-type-governed) method dispatch will then ensure that the (less specific) child method is called wins. Method arguments are assumed to be "consumed" and then PECS applies. Anyhow, for generic parameters, bridge methods are generated and it is all a bit more hairy. But we will get there.