1. What is reflection?
I remember a very popular explanation about reflection on the Internet :
Java is a big beauty, but there are many things that big women are not allowed to do. Reflex is to hold a gun, with a gun in hand, you can do whatever you want a big beauty to do, and it's okay to take off.
Normal explanation : Java's reflection means that the program can get all the information of an object at runtime. It is a method of dynamically obtaining object information and dynamically calling objects. The most common scenario is in dynamic proxies. The most widely used dynamic proxy is various frameworks, such as Spring.
2. Content and application of reflection
2.1 class object
Reflection must be inseparable from the Class object. We all know that after the code is written, it needs to be compiled into a .class file. Each .class file here exists as a Class object after being loaded into the memory by the virtual machine. A class can only have one .class file. Therefore, a class corresponds to a Class object, and the Class object is the description information of the class. For example: fields, methods, annotations, etc., as long as you want to get the class structure, he is reflected in the Class object, and can be obtained through the Class object.
总结:class
interface
The essence of (include ) is the data type ( Type
)
Taking a String
class as an example, when the JVM loads String
a class, it first reads String.class
the file into memory, then, String
creates an Class
instance of the class and associates it:
Class cls = new Class(String);
class
Since the JVM creates a corresponding instance for each loaded Class
instance, and saves class
all the information in the instance, including the class name, package name, parent class, implemented interfaces, all methods, fields, etc., therefore, if you obtain a certain An Class
instance, we can get all the information Class
corresponding to the instance through this instance .class
This method of Class
obtaining information through instances class
is called reflection.
How to get an class
instance of Class
one? There are three methods:
(1)
Get it directly through a class
static variable class
:
Class cls = String.class;
(2)
If we have an instance variable, we can get it through the getClass()
methods provided by the instance variable:
String s = "Hello";
Class cls = s.getClass();
(3)
If you know class
the full class name of one, you can get it through a static method Class.forName()
:
Class cls = Class.forName("java.lang.String");
Specific understanding: Class - Liao Xuefeng's official website
2.2 Proxy
Dynamic proxy is actually a process in which the JVM dynamically creates and loads class bytecodes at runtime.
Subsequent additions....