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

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

问题描述

static 成员(static 字段或 static 方法)与它们各自的类相关联,而不是与此类的对象相关联.以下代码尝试访问 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():

  • 评估 Primary 表达式,结果被丢弃.[...]
  • 如果该字段是非空的 final 字段,则结果是类或接口中指定类变量的值,即 Primary 表达式的类型. [...]
  • 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天全站免登陆