Accessing a static field with a NULL object in Java

前端 未结 3 586
独厮守ぢ
独厮守ぢ 2020-12-11 02:52

The following simple code snippet is working fine and is accessing a static field with a null object.

final class TestNull
{
    public static int field=100;         


        
3条回答
  •  生来不讨喜
    2020-12-11 03:36

    As opposed to regular member variables, static variables belong to the class and not to the instances of the class. The reason it works is thus simply because you don't need an instance in order to access a static field.

    In fact I'd say it would me more surprising if accessing a static field could ever throw a NullPointerException.

    If you're curious, here's the bytecode looks for your program:

    // Create TestNull object
    3: new             #3; //class TestNull
    6: dup
    7: invokespecial   #4; //Method TestNull."":()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 described in the Java Language Specification, Section 15.11.1: Field Access Using a Primary. They even provide an example:

    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

提交回复
热议问题