gpt4 book ai didi

java - 参数中带有通配符的不明确重载泛型方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:54:35 26 4
gpt4 key购买 nike

给出以下声明

interface Base<A> { }

interface Special<A,B> extends Base<A> { }

<T> void foo(Base<T> b) {}

<T> void foo(Special<?,T> s) {}

为什么我会得到以下代码的编译错误:

Special<String, Integer> s = null;
foo(s); // error: reference to foo is ambiguous

顺便说一句,可以通过将第二种方法的声明更改为来解决此问题

<T,X> void foo(Special<X,T> s) {}

最佳答案

首先,一个非常有趣的问题。

没有泛型

考虑以下代码:

interface NoGenericsBase { }

interface NoGenericsSpecial extends NoGenericsBase { }

interface NoGenericsSuperSpecial extends NoGenericsSpecial { }

void foo(NoGenericsBase b) {
System.out.println("Feel tha base");
}

void foo(NoGenericsSpecial s) {
System.out.println("Special delivery");
}

我们一直被告知编译器会选择最具体的方法。事实上,如果您调用 foo((NoGenericsSuperSpecial) null),上述代码将会执行。 , 打印以下内容:

Special delivery

到目前为止,还不错。

泛型

现在,让我们测试一些泛型行为:

interface Base<T> { }

interface Special<T> extends Base<T> { }

void foo(Base<? extends Number> b) {
System.out.println("Feel tha base");
}

void foo(Special<? extends Number> s) {
System.out.println("Special delivery");
}

public static void main(String[] args) {
Special<Integer> v = null;
new Main().foo(v);
}

此代码编译。编译器找到两个匹配项——都是 Base<? extends Number>作为Special<? extends Number> apply –,但编译器能够找出最具体的:它将选择 void foo(Special<? extends Number>) , 因为未绑定(bind)通配符的两个捕获是相等的。

但是让我们重写foo(Base<...>)方法并保持其余不变:

void foo(Base<? extends Integer> b) {
System.out.println("Feel tha base");
}

现在出现如下错误:

reference to foo is ambiguous
both method foo(Base<? extends Integer>) and method foo(Special<? extends Number>) match

在找出最具体的类型匹配之前,编译器会处理类型变量。显然,编译器无法确定 <? extends Number> 是否存在。或 <? extends Integer>适用,不考虑变量本身的类型(BaseSpecial)。

似乎变量类型处理先于关于继承的方法签名的选择。

一个人(或者至少我自己)应该期望编译器选择 foo(Special<? extends Number>) ,但事实并非如此。

原因

我不知道编译器是否无法选择关于泛型的最具体的一个,或者它没有配置为这样做。

参见 Java 语言规范 § 18.5§ 4.5.1了解更多详情。

让我花点时间阅读更多的泛型,也许我们可以弄明白...

关于java - 参数中带有通配符的不明确重载泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29211732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com