Search code examples
javaclassreflection

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.


Solution

  • 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 different way, and operations like instanceof function without having to instantiate a much heavier Class object, for performance reasons.