多个重载方法:null 是否等于 NullPointerException?

Multiple overloaded methods: Does null equal NullPointerException?

public class TestMain {

    public static void methodTest(Exception e) {
        System.out.println("Exception method called");
    }

    public static void methodTest(Object e) {
        System.out.println("Object method called");
    }

    public static void methodTest(NullPointerException e) {
        System.out.println("NullPointerException method called");
    }

    public static void main(String args[]) {
        methodTest(null);
    }   
}

输出:调​​用了 NullPointerException 方法

编译器将尝试匹配最具体的参数,在本例中为 NullPointerException。您可以在 Java 语言规范的 15.12.2.5 部分中查看更多信息。选择最具体的方法 :

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.

[...]

如果可能使用给定参数调用多个重载方法(在您的情况下为 null),编译器会选择最具体的一个。

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5

在你的情况下 methodTest(Exception e)methodTest(Object e) 更具体,因为 Exception 是 Object 的子类。 methodTest(NullPointerException e) 更具体。

如果将 NullPointerException 替换为 Exception 的另一个子类,编译器将选择那个子类。

另一方面,如果您创建一个额外的方法,例如 testMethod(IllegalArgumentException e),编译器将抛出错误,因为它不知道选择哪个。