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

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

问题描述

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

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 时,某些 IDE 会向您抛出该警告,因为对象实例不需要解析静态字段.

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编译器允许通过空对象访问静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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