Java reflection mechanism principle
"TLDR: This article explores the principles of Java's reflection mechanism and emphasizes its powerful ability to obtain class information at runtime. The article first introduces basic reflection code examples, and then provides an in-depth analysis of the reflection implementation process, including the compilation, loading and running phases. Finally, it is pointed out that since the object creation mechanism in Java involves Class class objects storing specific information of the class, reflection can achieve dynamic acquisition of class information."
If you want to find a programming language that uses reflection to the extreme, it must be Java. No other language uses reflection mechanisms so extensively, and C++ does not even provide reflection capabilities. Reflection's powerful ability to obtain class information at runtime provides the foundation for the Spring framework, and mechanisms such as AOP rely on it. However, we do not seem to have a deep understanding of where this ability of reflection comes from and how it is implemented.
First, basic reflection is obtained from the following code:
Class class = Class.forName("polo.User")
User user = (User) class.newInstance();
// Or use the constructor method
Constructor constructor = class.getConstructor();
User user = (User) constructor.newInstance();
From top to bottom, we see that the Class object is obtained first, and then the target object is obtained through the newInstance method of the Class object, so this involves the object creation mechanism in Java:
-
Compilation phase: source code.java —> source code.class, the class code we write will be compiled into a class bytecode file
-
Loading phase: When we need a new object, the JVM will first load the class to get the Class class object. Note that the Class class object here is not the object we need, but an object that corresponds to the source bytecode one-to-one and stores the specific information of the class, such as those member variables and those methods.
-Running phase: This is the phase where the objects we need are actually new.

Officially, because our class information will be stored in the form of Class class objects, Java can dynamically obtain the specific information of the class at runtime.
Class objects are stored in metaspace.
In C++, because there is no meta-information retained for each class and there is no Class class object, there is no reflection mechanism provided. If you want to implement it, you have to retain meta-information for each class yourself.