Java reflection mechanism
1、 Concept
Java reflection is a method by which a java program can load a class whose name is known only when it runs, obtain the complete construction method of the class, instantiate the object, set values for the object properties, or call the object. This function of dynamically obtaining class information and dynamically calling the method of the object at run time is called java reflection mechanism.
2、 Class class
Class class inherits from object class and is the entry of java reflection mechanism. It encapsulates the runtime information of a class or interface. You can get this information by calling the methods of class class. How to understand this class? If a common class is a collection of all object methods and attributes, this class can be understood as a collection of all common classes.
The following lists several methods to obtain class:
3、 Get class information
In order to test the reflection mechanism of Java, I created a new pair of parent-child classes, which covers four encapsulation attributes to test the acquisition of multiple types of information as much as possible:
1. Acquisition method
Class class obtains methods mainly in the following two ways:
Method [] getmethods() returns all accessible public methods (including inherited public methods) of the class or interface.
Method [] getdeclaredmethods() returns all methods of the class or interface (excluding inherited methods).
2. Get properties
Class obtains attributes mainly in the following two ways:
Field [] getfields(): store all accessible public properties (including inherited public properties) of the class or interface.
Field [] getdeclaredfields(): stores all properties of the class or interface (excluding inherited properties).
3. Get constructor
Class class obtains the construction method mainly in the following two ways:
Constructor [] getconstructors(): returns all public constructor methods of this class or interface
Constructor [] getdeclaraedconstructors(): returns all construction methods of the class or interface
4、 Dynamic call
So far, we have obtained the details of the corresponding class properties, methods and constructors through the methods of class. Next, we will use this information to dynamically create objects, modify properties and dynamically call methods.