带有null参数的Java方法调度 [英] Java method dispatch with null argument
问题描述
为什么我(显然)会直接传递 null
作为参数,或传递对象
我分配了值 null
?
Why does it (apparently) make a difference whether I pass null
as an argument directly, or pass an Object
that I assigned the value null
?
Object testVal = null;
test.foo(testVal); // dispatched to foo(Object)
// test.foo(null); // compilation problem -> "The method foo(String) is ambiguous"
public void foo(String arg) { // More-specific
System.out.println("foo(String)");
}
public void foo(Object arg) { // Generic
System.out.println("foo(Object)");
}
换句话说,为什么(注释掉)第二次调用 foo(...)
未发送到 foo(对象)
?
In other words, why is the (commented-out) second call to foo(...)
not dispatched to foo(Object)
?
更新:我使用的是Java 1.6。我可以毫无问题地编译Hemal的代码,但我仍然无法编译。我看到的唯一区别是Hemal的方法是静态的,而我的方法则不是。但我真的不明白为什么这会有所作为......?
Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?
更新2:已解决。我的类中有另一个方法foo(Runnable),因此调度程序无法明确地选择最具体的方法。 (请参阅我在Hemal的第二个答案中的评论。)感谢大家的帮助。
Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
推荐答案
您使用的是哪个版本的Java?使用1.6.0_11代码(粘贴在下面)编译并运行。
Which version of Java are you using? With 1.6.0_11 the code (pasted below) compiles and runs.
我确定其显而易见的原因 foo(testVal)
转到 foo(对象)
。
I am sure its obvious why foo(testVal)
goes to foo(Object)
.
foo(null)的原因
转到 foo(String)
有点复杂。常量 null
的类型为 nulltype
,这是所有类型的子类型。所以,这个 nulltype
扩展 String
,它扩展了 Object
。
The reason why foo(null)
goes to foo(String)
is a little complex. The constant null
is of type nulltype
, which is a subtype of all types. So, this nulltype
extends String
, which extends Object
.
当你调用 foo(null)
编译器会查找具有最特定类型的重载方法。由于 String
更具体,因此 Object
是被调用的方法。
When you call foo(null)
compiler looks for the overloaded method with most specific type. Since String
is more specific then Object
that is the method that gets called.
如果你有另一个特定于String的重载,比如说 foo(整数)
那么你会得到一个模糊的重载错误。
If you had another overload that was as specific as String, say foo(Integer)
then you would get a ambiguous overload error.
class NullType {
public static final void main(final String[] args) {
foo();
}
static void foo()
{
Object testVal = null;
foo(testVal); // dispatched to foo(Object)
foo(null); // compilation problem -> "The method foo(String) is ambiguous"
}
public static void foo(String arg) { // More-specific
System.out.println("foo(String)");
}
public static void foo(Object arg) { // Generic
System.out.println("foo(Object)");
}
}
这篇关于带有null参数的Java方法调度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!