模棱两可的方法调用 println 字符数组和字符串(而不是对象)

Ambiguous method call println char array and String (instead of Object)

public class Task03<K> {
        public <T> T foo() {
            try {
                return (T) new Integer(42);
            } catch (ClassCastException e) {
                return (T) new Integer(43);
            }
        }
        public static void main(String[] args) {
            Task03<?> v = new Task03<>();
            System.out.println(v.foo());
        }
}

我在第 System.out.println(v.foo()); 行有一个编译错误 不明确的方法调用:println(char[]) 和 println(String) 都匹配

我不清楚为什么 java 尝试使用这两种方法而不是 println(Object)println(int)

我们如何理解这种 java 编译器行为?

谢谢

Java 选择最具体适用的方法。因为 <T> 是在调用站点确定的,所以可以选择采用引用类型参数的任何 PrintStream.println 方法。

来自JLS 15.12.2.5

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

任何可以传递给println(char[])println(String)的东西也可以传递给println(Object),因此前者的方法比后者更具体。因此,这些将优先于 println(Object).

选择

然而,一些可以传递给 println(char[]) 的东西不能传递给 println(String),因此它们都不比另一个更具体,因此方法调用不明确。