java 静态变量 null,为什么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 object is null. Why this code is not throwing 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

You'll get:

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."":()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

}

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值