Basic understanding of Java reflection

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.

总结:classinterfaceThe essence of (include ) is the data type ( Type)

Taking a Stringclass as an example, when the JVM loads Stringa class, it first reads String.classthe file into memory, then, Stringcreates an Classinstance of the class and associates it:

Class cls = new Class(String);

classSince the JVM creates a corresponding instance for each loaded Classinstance, and saves classall 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 Classinstance, we can get all the information Classcorresponding to the instance through this instance .class

This method of Classobtaining information through instances classis called reflection.

How to get an classinstance of Classone? There are three methods:

(1)

Get it directly through a classstatic 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 classthe 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....

Guess you like

Origin blog.csdn.net/qq_35207086/article/details/123228659