加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

在Java中使用NULL对象访问静态字段

发布时间:2020-12-14 05:29:19 所属栏目:Java 来源:网络整理
导读:以下简单的代码片段正常工作,正在使用空对象访问静态字段. final class TestNull{ public static int field=100; public TestNull temp() { return(null); }}public class Main{ public static void main(String[] args) { System.out.println(new TestNull(
以下简单的代码片段正常工作,正在使用空对象访问静态字段.
final class TestNull
{
    public static int field=100;

    public TestNull temp()
    {
        return(null);
    }
}

public class Main
{
    public static void main(String[] args)
    {
        System.out.println(new TestNull().temp().field);
    }
}

在上面的代码中,声明System.out.println(new TestNull().temp().field);静态字段与NULL对象TestNull().temp()相关联,仍然返回正确的值为100而不是在Java中抛出空指针异常!为什么?

解决方法

与常规成员变量相反,静态变量属于类,而不属于类的实例.因此,它的原因是因为您不需要一个实例来访问静态字段.

实际上我会说,如果访问一个静态字段可能会抛出一个NullPointerException,我会更加惊讶.

如果你好奇,这是字节码寻找你的程序:

// Create TestNull object
3: new             #3; //class TestNull
6: dup
7: invokespecial   #4; //Method TestNull."<init>":()V

// Invoke the temp method
10: invokevirtual   #5; //Method TestNull.temp:()LTestNull;

// Discard the result of the call to temp.
13: pop

// Load the content of the static field.
14: getstatic       #6; //Field TestNull.field:I

这在Java Language Specification,Section 15.11.1: Field Access Using a Primary中有所描述.他们甚至提供了一个例子:

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

06001

It compiles,executes,and prints:

Mount Chocorua

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读