gpt4 book ai didi

java - 不明确的可变参数方法

转载 作者:太空宇宙 更新时间:2023-11-04 10:00:34 24 4
gpt4 key购买 nike

这是一个无法编译的代码示例:

public class Test {
public static void main(String[] args) {
method(1);
}

public static void method(int... x) {
System.out.println("varargs");
}

public static void method(Integer... x) {
System.out.println("single");
}
}

有人可以告诉我这些方法不明确的原因吗?预先感谢您。

最佳答案

重载决策中使用了 3 个阶段 ( JLS 15.2.2 ):

  1. The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

  2. The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.

  3. The third phase (§15.12.2.4) allows overloading to be combined with variable arity methods, boxing, and unboxing.

在您的示例中,两种方法都是可变数量方法,因此第三阶段适用。

现在,由于我们有两种方法可供选择,因此我们寻找更具体的方法。

JLS 15.12.2.5. Choosing the Most Specific Method说:

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

...

One applicable method m1 is more specific than another applicable method m2, for an invocation with argument expressions e1, ..., ek, if any of the following are true:

...

m2 is not generic, m1 and m2 are applicable by variable arity invocation, and where the first k variable arity parameter types of m1 are S1, ..., Sk and the first k variable arity parameter types of m2 are T1, ..., Tk, the type Si is more specific than Ti for argument ei for all i (1 ≤ i ≤ k). Additionally, if m2 has k+1 parameters, then the k+1'th variable arity parameter type of m1 is a subtype of the k+1'th variable arity parameter type of m2.

在您的情况下,您有两个非泛型方法,可通过变量参数调用应用(即两者都有可变参数)。为了在调用 method(1) 时选择其中一种方法,其中一种方法必须比另一种更具体。在您的情况下,每个方法只有一个参数,并且为了其中一个比另一个更具体,该一个参数的类型必须是另一个方法参数的子类型。

由于 int 不是 Integer 的子类型,并且 Integer 也不是 int 的子类型,因此您的方法都不比另一个方法更具体。因此,方法 method(int[]) 对于类型 Test 错误不明确。

一个可行的例子:

public static void method(Object... x) {
System.out.println("varargs");
}

public static void method(Integer... x) {
System.out.println("single");
}

由于IntegerObject的子类型,因此当您调用method(1)时将选择第二种方法。

关于java - 不明确的可变参数方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53556024/

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