为什么在使用空引用访问静态时不是 NullPointerException? [英] Why not a NullPointerException while accessing static with null reference?

查看:49
本文介绍了为什么在使用空引用访问静态时不是 NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我们在空引用上获取 i 的值,尽管 NPE 不存在.

Here in following code we are getting value of i on a null reference, though a NPE is not there.

public class Test {
    static int i = 10;

    Test getTest() {
        return null;    
    }

    public static void main(String args[]) {
        Test t = new Test();
        System.out.println(t.getTest());  
        System.out.println(t.getTest().i);
    }
}

输出

null
10

推荐答案

来自 Java 语言规范

接收器变量与静态字段访问无关

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

The following program demonstrates that a null reference may be used to access a class (static) variable without causing an exception:

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

它编译、执行和打印:

Mount Chocorua

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

即使在运行时计算主表达式(这里是实例),但它的值被丢弃并且只考虑它的类型.

Implies even though primary expression (Here is instance) is evaluated at run time, but its value is discarded and only its type is considered.

这篇关于为什么在使用空引用访问静态时不是 NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆