简体   繁体   English

调用Object.getClass()本身是否使用反射?

[英]Does calling Object.getClass() itself use Reflection?

My understanding is that java.lang.Class is the " entry point for all reflection operations ". 我的理解是java.lang.Class是“ 所有反射操作的入口点 ”。 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? 调用Object.getClass()还是本例中的something.getclass()使用反射还是仅仅是Class内部的方法使用反射?

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. 我会认为something.getClass()不使用反射,这是因为Class的引用已加载,而getClass只是该引用的获取方法,但我只是想确保。

According to the definition in Wikipedia: 根据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. 从这个角度来看, Object.getClass()本身就是反射,因为它可以用来检查给定的对象。

Checking the definitive source for Java's definition of reflection, the Java Language Specification , section 1.4. 检查Java反射定义的权威来源, Java语言规范 ,第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. 许多语言构造在Core Reflection API( java.lang.reflect )和Language Model API( javax.lang.model )中都有类似物,但此处一般不讨论。

The Java Virtual Machine Specification , section 2.12. Java虚拟机规范 ,第2.12节。 Class Libraries , says: 类库 ,说:

Classes that might require special support from the Java Virtual Machine include those that support: 可能需要Java虚拟机特殊支持的类包括那些支持以下内容的类:

  • Reflection, such as the classes in the package java.lang.reflect and the class Class . 反射,例如包java.lang.reflect的类和类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. 请注意,直到第一次调用它时, getClass()返回的Class对象才真正存在。 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. 由于性能原因, Class以不同的方式在内部存储,并且像instanceof函数之Class操作无需实例化更重的Class对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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