Annotation and reflection 02--Java reflection

Dynamic and Static Languages

To learn reflection, first we need to understand static and dynamic languages.
Dynamic language : a language whose structure can be changed at runtime: for example, new functions, objects, and even code can be introduced, existing functions can be deleted or other structural changes. The popular point is that the code can change its structure according to certain conditions at runtime.
Main dynamic languages: Object-C, C#, JavaScript, PHP, Python, etc.
Static language : Corresponding to dynamic language, a language whose runtime structure is immutable is a static language. Such as Java, C, C++.
Java is not a dynamic language, but Java can be called a "quasi-dynamic language". That is, Java has a certain degree of dynamism, and we can use the reflection mechanism to obtain characteristics similar to dynamic languages. The dynamic nature of Java makes programming more flexible.

get reflection object

Reflection (reflection) is the key to Java being regarded as a dynamic language. The reflection mechanism allows the program to obtain the internal information of any class by means of the Reflection API during execution, and can directly manipulate the internal properties and methods of any object.

Class c = Class.forName("java.lang.String")

After the class is loaded, an object of Class type is generated in the method area of ​​the heap memory (a class has only one Class object), and this object contains the complete structural information of the class. We can see the structure of the class through this heap. This object is like a mirror through which we can see the structure of the class, so we call it: reflection
insert image description here

Functions provided by the Java reflection mechanism

(1) Determine the class to which any object belongs at runtime.
(2) Construct an object of any class at runtime.
(3) Determine the member variables and methods of any class at runtime.
(4) Obtain generic information at runtime.
(5) Call member variables and methods of any object at runtime.
(6) Processing annotations at runtime.
(7) Generate dynamic proxy
(8)...

Advantages and disadvantages of Java reflection

Advantages: Dynamic object creation and compilation can be realized, showing great flexibility.
Cons: Has an impact on performance. Yes, reflection is basically an interpretation operation, we can tell the JVM what we want to do and it meets our requirements. Such operations are always slower than performing the same operations directly.

Main APIs related to reflection

(1) java.reflect.Method: represents the method of the class.
(2) java.long.Class: represents a class.
(3) java.reflect.Field: represents the member variable of the class.
(4) java.reflect.Constructor: represents the constructor of the class
(5)...

Guess you like

Origin blog.csdn.net/cang_ling/article/details/131961308