简体   繁体   中英

Does calling Object.getClass() itself use Reflection?

My understanding is that java.lang.Class is the " entry point for all reflection operations ". I also understand that when you instantiate a new object it will load the object's class if it's the first time it's needed.

Something something = new Something() 

Does calling Object.getClass() , or in our case something.getclass() , use reflection or is it just the methods inside Class itself that use reflection?

I would think that something.getClass() does not use reflection due to the fact that the Class's reference has been loaded and getClass would just be a getter for this reference, but I just want to make sure.

According to the definition in Wikipedia:

In computer science, reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at runtime.

From this point of view, Object.getClass() is reflection per se since it can be used to examine the given object.

Checking the definitive source for Java's definition of reflection, the Java Language Specification , section 1.4. Relationship to Predefined Classes and Interfaces , simply says:

Consequently, this specification does not describe reflection in any detail. Many linguistic constructs have analogs in the Core Reflection API ( java.lang.reflect ) and the Language Model API ( javax.lang.model ), but these are generally not discussed here.

The Java Virtual Machine Specification , section 2.12. Class Libraries , says:

Classes that might require special support from the Java Virtual Machine include those that support:

  • Reflection, such as the classes in the package java.lang.reflect and the class Class .

So, you use reflection if you:

Note that the Class object returned by getClass() doesn't actually exist until you call it the first time. Classes are internally stored in a difference way, and operations like instanceof functions without having to instantiate the much heavier Class object, for performance reasons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM