为什么Java编译器允许通过null对象进行静态变量访问? [英] Why does Java compiler allow static variable access through null object?

查看:196
本文介绍了为什么Java编译器允许通过null对象进行静态变量访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我指着一些技巧并遇到了这个。在以下代码中:

I was pointing some tricks and came across this. In following code:

public class TestClass1 {

    static int a = 10;

    public static void main(String ar[]){
        TestClass1 t1 = null ;
        System.out.println(t1.a); // At this line
    }
}

t1 对象是 null 。为什么这段代码没有抛出 NullPointerException

t1 object is null. Why this code is not throwing NullPointerException?

我知道这不是正确的方法来访问 static 变量,但问题是关于 NullPointerException

I know this is not proper way to access static variables but question is about NullPointerException.

推荐答案

如果您使用以下方式反汇编类文件,请在当前答案中添加一些其他信息:

To add some additional info to the current answers, if you disassemble your class file using:

javap -c TestClass1

你会得到:

Compiled from "TestClass1.java"
public class TestClass1 extends java.lang.Object{
static int a;

public TestClass1();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   aconst_null
   1:   astore_1
   2:   getstatic   #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   5:   aload_1
   6:   pop
   7:   getstatic   #3; //Field a:I
   10:  invokevirtual   #4; //Method java/io/PrintStream.println:(I)V
   13:  return

static {};
  Code:
   0:   bipush  10
   2:   putstatic   #3; //Field a:I
   5:   return
}

在这里你可以看到通过 getstatc 指令在第7行完成对静态字段的访问。每当通过代码访问静态字段时,相应的 <将在 .class 程序文件中生成code> getstatic 指令。

Here you can see that the access to the static field is done in line 7 by the getstatc instruction. Whenever a static field is accessed through code, a corresponding getstatic instruction will be generated in the .class program file.

* static 说明具有特殊性,即他们不需要对象中的对象实例的引用在调用它们之前进行堆栈(比如,例如需要堆栈中的对象引用的invokevirtual),它们仅使用运行时间常数池,稍后将用于解决现场参考位置。

*static instructions have the particularity that they don't requiere a reference to the object instance to be in the stack prior to calling them (like, for example invokevirtual which does require an object ref in the stack), they resolve the field/method using just an index to the run time constant pool that will be later used to solve the field reference location.

这是警告的技术原因应该以静态方式访问静态字段当你写 t1.a ,因为对象实例不需要解析静态字段。

That's a technical reason for the warning "The static field should be accessed in a static way" that some IDEs will throw at you when you write t1.a, because the object instance is unnecessary to resolve the static field.

这篇关于为什么Java编译器允许通过null对象进行静态变量访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆