foo(int,int)被挑选在foo(int ...)上
在此代码中,为什么编译器无法引用从静态上下文中具有varargs参数的方法。
private static void doSomething(int... nums) {
System.out.println("1");
}
private void doSomething(int num1, int num2) {
System.out.println("2");
}
public static void main(String[] args) {
doSomething(1,2);
}
JDK 17正在抱怨无法对非静态方法(int,int)
进行静态引用。这是我不知道的错误还是另一个功能。
JDK 8和JDK 11不要抱怨它!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
拒绝该方法调用的行为是正确的。方法分辨率应首先找到最特定的方法,然后检查以后
static
修饰符。但是
javac
从版本7到16中都有一个错误。请参见
jdk -8268474,方法分辨率应停止静态错误
该错误已用JDK  17修复。
请注意,Eclipse的编译器ECJ没有此错误,因此无论您使用哪种JDK版本,该示例在Eclipse中被拒绝。
仅使用简单名称的调用受到影响。当您使用
className.dosomething(1,2);
时,所有版本都将把调用解析为dosomething(int num1,int num2)
并生成正确的错误。The behavior of rejecting the method invocation is correct. Method resolution should find the most specific method first and check for the
static
modifier afterwards.But there is a bug in
javac
from version 7 to 16.See
JDK-8268474, Method resolution should stop on static error
This bug has been fixed with JDK 17.
Note that Eclipse’s compiler ECJ does not have this bug, so the example is rejected in Eclipse, regardless of which JDK version you use.
Only invocations using a simple name are affected. When you use
ClassName.doSomething(1,2);
, all versions will resolve the invocation todoSomething(int num1, int num2)
and generate the correct error.使用两个INT的滴定方法是一种实例方法,您正在尝试不先创建对象实例的情况。
为什么编译器应该接受?我高度怀疑,在任何先前的JDK中,其行为都不同。
The doSomething method which takes two ints is an instance method and you are trying to call it without creating an instance of the object first.
Why should the compiler accept that? I highly doubt, that in any prior JDK it behaved differently.
一种静态方法只能调用其他静态方法。它无法调用非静态方法。 ,这就是为什么
non static
dosomething
函数始终被调用的原因。为了调用
dosomething(int,int)
,您必须将其制作static
或创建包含该方法的类的对象,然后使用对象调用该方法。A static method can call only other static methods; it cannot call a non-static method. So that's why the
non-static
doSomething
function is always called.In order to call the
doSomething(int, int)
you have to make itstatic
or create an object of the class containing the method and then call the method using the object.varargs是数组的替代。编译器正在给您错误,因为您以varargs不可接受的方式调用
dosomething
:要调用varargs方法,您应该调用类似的内容:
通过这种方式,您将正确调用
>私有静态空白(int ... nums)
在JDK8(8U41)&在JDK17上。
此外,调用
dosomething(1,2)
在JDK8& JDK17,所以我在两个版本上都没有发现任何不同的东西。varargs are replacement for arrays. Compiler is giving you error because you are calling
doSomething
in a manner which is not acceptable for varargs:To call your varargs method you should call something like:
By this way, you will be correctly calling
private static void doSomething(int... nums)
Tested this in JDK8 (8u41) & on JDK17.
Moreover, calling
dosomething(1,2)
is giving error on both JDK8 & JDK17 so I am not finding anything different on both versions.