我们可以在Java中使用null对象调用静态方法吗?如果是这样,怎么样?

ver*_*raj 8 java static

由于静态方法可以直接从类中调用(即ClassName.methodName),为什么需要使用类的对象调用静态方法?

如果有人知道,请举例说明.

public static void methodA(){

}
Run Code Online (Sandbox Code Playgroud)

nos*_*sid 16

以下代码包含一个示例,其中通过null引用调用静态方法.

public class Test {
    public static void main(String... args) {
        Test test = null;
        test.greeting(); // call with null reference
    }
    public static void greeting() {
        System.out.println("Hello World");
    }
}
Run Code Online (Sandbox Code Playgroud)

因为Test::greeting是静态方法,所以表达式test.greeting()是相同的Test.greeting().因此,NullPointerException在运行时没有抛出.


Sur*_*tta 10

调用静态成员或方法时不需要实例.

由于静态成员属于类而不是实例.

Example 15.11.1-2. Receiver Variable Is Irrelevant For static Field Access

以下程序演示了可以使用null引用来访问类(静态)变量而不会导致异常:

这个例子来自于自我规范.

class Test3 {
    static String mountain = "Chocorua";
    static Test3 favorite(){
        System.out.print("Mount ");
        return null;
    }
    public static void main(String[] args) {
        System.out.println(favorite().mountain);
    }
}
Run Code Online (Sandbox Code Playgroud)

并分析其发生的原因

即使favorite()的结果为null,也不会抛出NullPointerException.打印"Mount"表明主表达式确实在运行时完全评估,尽管事实上只使用其类型而不是其值来确定要访问的字段(因为字段山是静态的).


Dix*_*gla 5

很好,您可以使用null对象调用静态方法。

请参见下面的示例。

public class Hashing {

    public static void Hash() {
        System.out.println("hello");
    }

    public static void main(String[] args) {
        Hashing h = null;
        h.Hash();
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码片段将打印你好

因为在编译时h.hash()将被转换为Hashing.hash()由于hash()是一个静态方法。

当我反编译.class文件时,我得到了这段代码。

/*
 * Decompiled with CFR 0_114.
 */
import java.io.PrintStream;

public class Hashing {
    public static void Hash() {
        System.out.println("hello");
    }

    public static void main(String[] args) {
        Object h = null;
        Hashing.Hash();
    }
}
Run Code Online (Sandbox Code Playgroud)

正如你可以在上面的代码片段看到h.Hash();被转换成Hashing.Hash();

HTH!