Java 通配符的语言规范

Java language specification on wildcards

我正在阅读这个 link(第 4 章。类型、值和变量)但不明白以下几点:

The relationship of wildcards to established type theory is an interesting one, which we briefly allude to here. Wildcards are a restricted form of existential types. Given a generic type declaration G<T extends B>, G<?> is roughly analogous to Some X <: B. G<X>.

如果您能提供很好的例子来清楚地理解上述观点,我将不胜感激。

提前致谢。

通配符是存在类型的一种限制形式,它们在 Java 中结合了存在类型的原则。您可以参考 link 这里提供的解释性示例: What is an existential type?

这句话的措辞和格式有点不吉利* 中的 link 实际上很好地涵盖了一般主题,但可以尝试着重于 Java 和通配符的特殊情况:

Wildcards are a restricted form of existential types. Given a generic type declaration G, G is roughly analogous to Some X <: B. G.

这基本上是说 G 的类型参数是 B 的任何子类型。 总是 情况,即使您没有明确说明。

考虑以下片段,它有望说明这一点:

class B { } 
class G<T extends B> 
{
    T get() { return null; }
}

public class Example
{
    public static void main(String[] args)
    {
        G<?> g = null;

        // This works, even though "G<?>" seemingly does not say 
        // anything about the type parameter:
        B b = g.get();
    }
}

调用g.get()得到的对象是B类型,因为G<T extends B>声明保证了任何类型参数(即使它是 ? 通配符)总是 "at least" 类型 B.

(与之相反:如果声明只有G<T>,那么从g.get()得到的类型也只会是Object类型)


这种关系被描述为与类型理论符号“大致类似”。你大概可以想象这句话:如果声明是G<T extends B>,而你使用类型G<?>,那么这大致(!)意味着:存在一个类型X extends B,并且? 这里代表这个(未知的)类型 X


旁白:请注意,这也指的是 Insersection Types。如果您将 class 声明为 class G<T extends B & Runnable>,则语句

B b = g.get();
Runnable x = g.get();

两者都有效。


* "unlucky"格式指的是本段源码实际上是

    ... is roughly analogous to <span class="type">Some <span class="type">X</span> ...

更清楚地表明 "Some" 这个词已经是那里正式定义的 类型 的一部分...