Wechat search “Java fish”, a knowledge point every day not bad
(1) One knowledge point every day
How does reflection work, what are the three ways that reflection creates class instances?
(2) Answer
2.1 What is Reflection
A piece of Java code running on a computer is divided into the following three processes:
Stage 1. Source:
At this stage, Javac compiles the Java code into a class file, which is stored on hard disk. This file holds the class name, member names, constructors, other methods, and so on.
2. The phase of the Class
The Class phase transforms the information in the Class bytecode file into Class objects, such as member variables held by Field[], constructors held by Constructor[], and member methods held by Method[].
3. The Runtime phase
Create the actual object from the class object of the second stage in the code through the new method.
The second stage here, encapsulating the various components of a class into other objects, is reflection.
2.2 What are the three ways to create class instances by reflection
There are three ways to get a Class object, corresponding to the previous three stages:
1. The method corresponding to the first stage is to load the bytecode file into memory:
class.forname("All class name");
Copy the code
2. The second phase has generated the class object, so the method is as follows:
The name of the class. The class;Copy the code
3. The third stage generates objects as follows:
Object. Getclass ();Copy the code
Note: The same bytecode file (.class) is loaded only once during a program run, and the class object created using the above three methods is the same.
I wrote a blog post about reflex mechanisms:
The Java core foundation Java reflection mechanism in detail