Java:调用静态方法,但编译错误:非静态方法&#xxxx无法从静态上下文中引用
我的测试代码:
class Test1{
public void a(String a) {
}
public static void a(String a, Object... objects) {
}
public static void b(String a, Object... objects) {
}
public static void main(String[] args) {
Test1.a(""); // call static a(), compile error: Non-static method 'a(java.lang.String)' cannot be referenced from a static context
Test1.b(""); // it is working.
}
}
为什么发生此错误?为什么 jdk 找到静态方法a()
?如何解决此错误?
My test code:
class Test1{
public void a(String a) {
}
public static void a(String a, Object... objects) {
}
public static void b(String a, Object... objects) {
}
public static void main(String[] args) {
Test1.a(""); // call static a(), compile error: Non-static method 'a(java.lang.String)' cannot be referenced from a static context
Test1.b(""); // it is working.
}
}
Why did this error occur? Why didn't JDK find static method a()
? how to fix this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您对
a()
的调用具有一个字符串参数。您的实现
a()
带有(i)一个字符串参数,或(ii)一个字符串参数加上零或更多对象。案例(i)是通话更具体的匹配。
确定呼叫指的方法是描述的在JLS 中。
如何修复?您需要解决歧义。您可以致电某种假人的论点。但是,我的选择是不要将相同的名称“ A”用于静态和非静态方法。
否则使“ A”方法同时静态 - 可以满足编译器的满足,但是如果
a(“”)
anda(“”,“,”,“,” ”)
具有完全无关的动作。但是,当然,这始终是超载名称的考虑因素。但是“为什么”这样呢?
test1.a(...)
是静态成员的调用,因为它带有类名称而不是实例参考,这不是很明显吗?也许。但是,请考虑一下,在类中,您可以在没有类名的情况下称呼静态方法,并且可以在没有“此”的情况下称为非静态方法。也就是说,调用
foo()
可以指静态方法或非静态方法。因此,通常,解决超载的名称必须考虑静态和非静态可能性。我们正在考虑的情况是遵守一般规则(即使人们可能认为它不需要这样做 - 但这对语言设计师来说是一个问题)。Your call to
a()
has one String argument.You have implementations of
a()
with (i) one String argument, or (ii) one String argument plus zero or more Objects.Case (i) is a more specific match for the call.
Determining which method a call refers to is described here in the JLS.
How to fix? You need to resolve the ambiguity. You could give the call some sort of dummy argument. My choice, however, would be to not use the same name 'a' for a static and non-static method.
Or else make both the 'a' methods static -- that would satisfy the compiler, but it might make it difficult to use, if
a("")
anda("", "")
have completely unrelated actions. But that of course is always a consideration for overloading names.But 'why' is it like this? Isn't it obvious that
Test1.a(...)
is a call on a static member, since it is prefixed with a class name rather than an instance reference?Perhaps. But consider that within a class, you can call a static method without the class name as a qualifier, and you can call a non-static method without 'this' as a qualifier. That is, a call
foo()
could refer to either a static method or a non-static method. So in general, resolving an overloaded name must consider both static and non-static possibilities. The case we're looking at is obeying the general rule (even though one might argue that it need not do so - but that's a matter for the language designers).