First, what is reflection
The dynamic acquisition of information for a class and the method of dynamically invoking the object are called the Java Reflection (Reflection) mechanism. Reflection provides an object that encapsulates assemblies, modules, and types. In the Java Runtime Environment, for objects of any class, you can get information about this class through reflection.
Second, the role of reflection
The Java reflection mechanism allows the program to obtain internal information for any given class, including modifiers (public, static, and so on), superclass (such as Object), through the reflection APIs at run time, Implemented interfaces (such as Serializable), fields (attributes), and methods (methods), but not methods definitions, can change the contents of fields at run time, or you can call methods.
Iii. Introduction to the Java Reflection API
In the JDK, the Java reflection mechanism is implemented primarily by the following classes:
①class class: Represents a Class;
②field class: A member variable (attribute) representing a class;
③method class: Methods for representing classes;
④constructor class: The construction method of the Representative class;
⑤array class: Provides a static method for dynamically creating arrays and accessing array elements;
In the class above, class is in the Java.lang package and the rest is in the Java.lang.reflect package.
The Java.lang.Object class (the superclass of all classes) defines the GetClass () method, which can be used by any Java object to obtain its class.
Class is the core class in the Reflection API, which has the following main methods:
①getname (): Gets the name of the class;
②getfields (): Gets the properties of the public type in the class;
③getdeclaredfields (): Gets all the properties of the class (including public, protected, default, private);
④getmethods (): Gets the method of the public type in the class;
⑤getdeclaredmethods (): Gets all the methods of the class;
⑥getmethod (String name,class[] parametertypes): Gets the specified method of the class, name: The name of the specified method, ParameterType: The parameter type of the specified method;
⑦getconstrutors (): Gets the construction method of the public type in the class;
⑧getconstrutor (class[] parametertypes): Gets the specified constructor method for the class, Parametertypes: Specifies the parameter type of the constructor method;
⑨newinstance (): Creates an object of the class by using the class's default construction method without parameters;
Note: When accessing private properties and private methods, a private property or method setting for access requires that the setAccessible(true) reflected class suppress the access check mechanism for Java. Otherwise, an IllegalAccessException exception is reported.
Analysis of Java Reflection mechanism