Using null objects to access static fields in Java

The following simple code snippet works properly and is using an empty object to access static fields

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);
    }
}

In the above code, declare system out. println(new TestNull(). temp(). field); Static field and null object testnull() Temp() and still returns the correct value of 100 instead of throwing a null pointer exception in java! Why?

Solution

In contrast to regular member variables, static variables belong to classes, not instances of classes The reason for this is that you do not need an instance to access static fields

In fact, I would say that I would be even more surprised if accessing a static field might throw a NullPointerException

If you're curious, this is bytecode looking for your program:

// 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

This is in the Java language specification, section 15.11 1: Field access using a primary is described They even provided an example:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>