java - 为什么不调用从返回 null 的静态方法链接的静态变量抛出 NPE?

标签 java static null

我有以下代码

public class Test {
    static String mountain = "Everest";

    static Test favorite() {
        System.out.print("Mount ");
        return null;
    }

    public static void main(String[] args) {
        System.out.println(favorite().mountain);
    }
}

我认为它会引发一个NPE,但它给出了Mount Everest作为输出,任何人都可以澄清吗?

最佳答案

碰巧您可以访问对象引用上的静态成员。在这种情况下,成员根据引用的类型而不是它的值来解析。

Java Language Specification关于 static 成员的字段访问

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.

If the field is not final, or is a blank final and the field access occurs in a constructor, then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.

所以 Primary,即实例,并不重要。

关于java - 为什么不调用从返回 null 的静态方法链接的静态变量抛出 NPE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20649322/

相关文章:

java - Spring 启动: Testing a service with Constructor Dependency Injection

php - 在php中使用静态类变量作为类名调用静态方法

sql-server - MS SQL 2008 将 null 转换为字符串

java - 为什么抽象变量 null 不等于 null

java - 当对象具有不同的 serialVersionUID 时,如何反序列化持久保存在数据库中的对象

java - 在java中实现同步addAll到列表

java - 如何在 Java 中不使用正则表达式来处理不区分大小写的字符串替换

c++ - 如何只执行一次代码?

c# - 关于c#中的静态类

c# - 类属性默认值(如果未分配)