带有null参数的Java方法调度

Yan*_*yer 13 java null method-dispatch

为什么它(显然)有所作为是否我通过null直接作为参数,或者传递一个Object,我分配的价值 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)");
}
Run Code Online (Sandbox Code Playgroud)

换句话说,为什么第二次调用(已注释掉)foo(...)未调度到foo(Object)?

更新:我使用Java 1.6.我可以毫无问题地编译Hemal的代码,但我仍然无法编译.我看到的唯一区别是,Hemal的方法是静态的,而我的方法则不是.但我真的不明白为什么这应该有所作为......?

更新2:解决了.我的班级中有另一个方法foo(Runnable),因此调度员无法明确地选择最具体的方法.(请参阅我在Hemal的第二个答案中的评论.)感谢大家的帮助.

Mis*_*ble 24

您使用的是哪个版本的Java?使用1.6.0_11代码(粘贴在下面)编译并运行.

我肯定很明显为什么foo(testVal)会这样foo(Object).

为什么原因foo(null)去foo(String)有点复杂.常量null是类型nulltype,它是所有类型的子类型.因此,这nulltype延伸String,延伸Object.

当您调用foo(null)编译器查找具有最特定类型的重载方法时.因为String更具体Object,那就是被调用的方法.

如果你有另一个特定于String的重载,foo(Integer)那么你会得到一个模糊的重载错误.

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)");
  }

}
Run Code Online (Sandbox Code Playgroud)