Java reflection mechanism and java reflection
1. What is reflection?
DynamicObtain the class information andDynamicThe method of calling an object is called the Java Reflection mechanism. Reflection provides encapsulated assembly, module, and type objects. In JavaRuntimeIn the environment, for any class object, the class information can be obtained through reflection.
Ii. Functions of reflection
The Java Reflection mechanism allows the program to obtain internal information of any class with a known name through Reflection APIs at runtime, including modifiers (such as public and static), superclass (such as Object), Implemented interfaces (such as Serializable), fields (attribute), and methods (method) (but does not include methods definitions), you can change the content of fields at runtime, or you can call methods.
Iii. Java Reflection API Introduction
In JDK, the Java reflection mechanism is implemented mainly by the following classes:
① Class: represents a Class;
② Field Class: represents the member variables (attributes) of the class );
③ Method class: indicates the Method of the class;
④ Constructor class: Constructor class;
⑤ Array class: provides static methods for dynamically creating arrays and accessing Array elements;
Among the above classes, the Class is in the java. lang package, and the rest are in the java. lang. reflect package.
The java. lang. Object class (the superclass of all classes) defines the getClass () method. Any Java Object can obtain its class through this method.
The Class is the core Class in the Reflection API and mainly includes the following methods:
① GetName (): Get the class name;
② GetFields (): Get the public type attribute in the class;
③ GetDeclaredFields (): obtains all attributes of a class, including public, protected, default, and private );
④ GetMethods (): gets the public type method in the class;
⑤ GetDeclaredMethods (): Get all methods of the class;
⑥ GetMethod (String name, Class [] parameterTypes): gets the specified method of the Class, name: Specifies the name of the method, parameterType: Specifies the parameter type of the method;
7. getConstrutors (): obtains the public Type constructor in the class;
Required getConstrutor (Class [] parameterTypes): gets the specified constructor of the Class. parameterTypes: Specifies the parameter type of the constructor;
⑨ NewInstance (): creates an object of the class through the default constructor without parameters;
Note: When accessing private attributes and private methods, you must set Private attributes or methods for access.setAccessible(true)
Causes the reflected class to suppress java's access check mechanism. Otherwise, an error is reported.IllegalAccessException
Exception.