Java:重载方法解析和varargs - 令人困惑的例子 [英] Java: overloaded method resolution and varargs -- confusing example
问题描述
就在我认为我理解的时候 JLS15.12 因为它应用于varargs,这是这个例子:
Just when I thought I understood JLS15.12 as it applied to varargs, here's this example:
package com.example.test.reflect;
public class MethodResolutionTest2 {
public int compute(Object obj1, Object obj2) {
return 42;
}
public int compute(String s, Object... objects)
{
return 43;
}
public static void main(String[] args) {
MethodResolutionTest2 mrt2 = new MethodResolutionTest2();
System.out.println(mrt2.compute("hi", mrt2));
System.out.println(mrt2.compute("hi", new Object[]{mrt2}));
System.out.println(mrt2.compute("hi", new Object[]{mrt2, mrt2, mrt2}));
}
}
打印出来
42
43
43
我理解第一行: JLS15.12 表示方法解决分阶段进行,第1阶段和第2阶段忽略了varargs方法,以确定是否存在兼容方法,仅当阶段1和阶段2失败时才会发生阶段3(包括变量)。 (参见JLS和这个问题。)所以 compute(String s,Object ... objects)
总是被忽略如果 compute(Object obj1,Object obj2)
适用。
I understand the first line: JLS15.12 says method resolution happens in phases, and phases 1 and 2 ignore varargs methods to find out if there's a compatible method, with phase 3 (include varargs) happening only if phases 1 and 2 fail. (See the JLS and this SO question.) So compute(String s, Object... objects)
always gets ignored if compute(Object obj1, Object obj2)
applies.
但我不明白为什么43为其他两行打印。 Object []
也是 Object
的实例,为什么它与varargs方法匹配?
But I don't understand why 43 is printed for the other two lines. An Object[]
is also an instance of an Object
, so why does it match the varargs method?
编辑:
...这个
Object arg2 = new Object[]{mrt2};
System.out.println(mrt2.compute("hi", arg2));
打印 42
。
推荐答案
在 8.4.1 :
如果最后一个形式参数是变量arity参数类型
T
,
它被认为是定义类型为T []
的形式参数。
由于你明确提供了一个数组,这允许后两个调用在第一阶段匹配变量arity方法,而不需要考虑变量arity。
Since you're explicitly providing an array, this allows the second two calls to match the variable arity method in the first phase, without consideration of variable arity.
这篇关于Java:重载方法解析和varargs - 令人困惑的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!