Java中空引用的静态字段 [英] Static fields on a null reference in Java

查看:141
本文介绍了Java中空引用的静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

static 成员(静态字段或静态方法在Java中,它们与它们各自的类相关联,而不是与该类的对象相关联。以下代码尝试访问 null 引用上的静态字段。

static members (static fields or static methods) in Java are associated with their respective class rather than the objects of this class. The following code attempts to access a static field on a null reference.

public class Main
{
    private static final int value = 10;

    public Main getNull()
    {
        return null;
    }

    public static void main(String[] args)
    {
        Main main=new Main();
        System.out.println("value = "+main.getNull().value);
    }
}

虽然 main.getNull( )返回 null ,它可以工作并显示 value = 10 。这段代码是如何工作的?

Although main.getNull() returns null, it works and displays value = 10. How does this code work?

推荐答案

该行为在 Java语言规范


空引用可用于访问类(静态)变量而不会导致异常。

a null reference may be used to access a class (static) variable without causing an exception.

更多详细信息,静态字段评估,例如 Primary.staticField 的工作方式如下(强调我的) - 在您的情况下, Primary = main.getNull( )

In more details, a static field evaluation, such as Primary.staticField works as follows (emphasis mine) - in your case, Primary = main.getNull():



  • 评估主表达式,结果被丢弃。 [...]

  • 如果该字段是非空白的最终字段,那么结果是类或接口中指定类变量的值主要表达。 [...]

  • The Primary expression is evaluated, and the result is discarded. [...]
  • If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression. [...]

这篇关于Java中空引用的静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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