简体   繁体   English

模糊的varargs方法调用编译错误

[英]Ambiguous varargs method call compilation error

method(1);  // This works -

void method(int... x) { }
void method(int x) { }  // - this method is called

If I add a varargs parameter to the second method, I get a "reference to method is ambiguous" compilation error: 如果我向第二个方法添加一个varargs参数,我得到一个“方法参考不明确”的编译错误:

method(1);  // This now fails

void method(int... x) { }
void method(int x, String... y) { }  // adding String... y causes a problem.

As the String... y argument(s) can be left "blank", why doesn't Java still pick that method? 由于String ... y参数可以保留为“空白”,为什么Java仍然没有选择该方法? Thanks, and apologies if there is a closely matching explanation on SO; 谢谢,如果对SO有一个非常匹配的解释,我们会道歉; I did look for one. 我确实找了一个。

The compiler always makes the choice to use the most specific method. 编译器总是选择使用具体的方法。

In the first case, because the number of the arguments exactly matches void method(int x) , it is the one that's being called. 在第一种情况下,因为参数的数量void method(int x) 完全匹配,所以它是被调用的那个。

In the second case, the number of the arguments don't match any case, and it can be called from both methods, resulting the ambiguity. 在第二种情况下,参数的数量与任何情况都不匹配,并且可以从两种方法调用它们,从而导致歧义。

Check the JLS - 15.12.2. 检查JLS - 15.12.2。 Compile-Time Step 2: Determine Method Signature for details. 编译时步骤2:确定方法签名以获取详细信息。

The number of arguments can be 0 or many. 参数的数量可以是0或许多。 which makes 这使得

void method(int x, String... y){ } is similar to void method(int x){} void method(int x, String... y){ }类似于void method(int x){}

And the 而且

void method(int... x){} is also similar to void method(int x){} void method(int... x){}也类似于void method(int x){}

If you call method(1), the compiler will find two applicable method to this call and raises and exception. 如果调用方法(1),编译器将找到两个适用于此调用的方法,并引发和异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM