gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:50:55 25 4
gpt4 key购买 nike

以下简单的代码片段工作正常,并且正在使用 null 对象访问静态字段。

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);,其中静态字段field与NULL对象new 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:

class Test {
static String mountain = "Chocorua";
static Test favorite(){
System.out.print("Mount ");
return null;
}
public static void main(String[] args) {
System.out.println(favorite().mountain);
}
}

It compiles, executes, and prints:

Mount Chocorua

关于java - 在 Java 中使用 NULL 对象访问静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54766013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com