开发者

What happens under the hood when call Class.class.getClass()?

开发者 https://www.devze.com 2023-03-18 00:34 出处:网络
It\'s not hard to understand String.class.getClass(), which mean return a Class Object that represent 开发者_如何学运维the run time class of String Object. But what\'s going on when calling Class.clas

It's not hard to understand String.class.getClass(), which mean return a Class Object that represent 开发者_如何学运维the run time class of String Object. But what's going on when calling Class.class.getClass(), can I apprehend it as returning a Class object that represent the run time class of Class object itself? How can this be implemented in Java reflection API?


a Class object that represent the run time class of Class object itself?

Yes.

But String.class.getClass() is the same thing.

String.class already means "the object of type Class that represents the String class". Calling .getClass() on that means "the object of type Class that represents the Class class", because we're calling it on an object of type Class.

If you have an object that is a String, for example "hi mom", then you can reflect it with .getClass(): ("hi mom").getClass() for example. IIRC, this will return the exact same object as String.class in normal circumstances, because there is only one Class object per class (, per ClassLoader in use).

How can this be implemented in Java reflection API?

Every time the bytecode for a class is loaded, a Class object is created and associated with that bytecode. Every object conceptually keeps a "hidden" reference to the Class instance that represents its class, that is automatically set by the constructor. Class objects have this reference set to a Class object that represents the Class class. In particular, the Class object that represents the Class class has a reference to itself.


can I apprehend it as returning a Class object that represent the  run time class of Class object itself?

No. Object.class.getClass() is same as Class.class.getClass().

    System.out.println(Object.class.getClass() == Class.class.getClass()); // true
0

精彩评论

暂无评论...
验证码 换一张
取 消