(Java Reflection Reflection)
Reflection: The soul of frame design
* Framework: semi-finished software. * Reflection: Encapsulates the various components of a class into other objects. This is the reflection mechanism * Benefits: 1. These objects can be manipulated while the program is running. 2. Can be decoupled, improve the scalability of the program. 1. Class.forname (" full Class name ") : load the bytecode file into memory, return the Class object * for configuration files, define the Class name in the configuration file. Class: get * from the class name attribute * for passing parameters 3. Object. GetClass () : The getClass() method is defined in the Object class. 4.ClassLoader cl = this.getClass().getClassLoader(); Class clazz = cl.loadClass(" full Class name ") * Conclusion: The same bytecode file (*.class) is loaded only once during a program run, and the Class object is the same regardless of which way it is retrieved. 1. Get member variables * Field[] getFields() : Field getField(String name) getDeclaredFields() getDeclaredFields() getDeclaredFields() getDeclaredFields() getDeclaredFields() Field getDeclaredField(String name) 2. Get constructors * Constructor<? >[] getConstructors() * Constructor<T> getConstructor(class <? >... ParameterTypes * Constructor<T> getDeclaredConstructor(class <? >... parameterTypes) * Constructor<? >[] getDeclaredConstructors() 3. GetMethod (String name, class <? >... ParameterTypes) * Method[] getDeclaredMethods() * Method getDeclaredMethod(String name, class <? >... ParameterTypes = String getName() * Field: member variable * * void set(Object obj, Object value) 2. * get(Object obj) 3. Ignore the security check of the access modifier * setAccessible(true): violence reflection * Constructor: creating an Object: * T newInstance(Object... Initargs) * If you use the null argument constructor to create an Object, the operation can be simplified: Class Object newInstance Method * Method: Method Object * Execution Method: * Object invoke(Object obj, Object... Args) * getName: String getName: getNameCopy the code
First, provide functions
- The runtime determines which class the object belongs to
- Construct any class object at run time
- The runtime determines which member variables and methods any class has
- Get generic information at run time
- The runtime invokes variable methods of arbitrary objects
- Deal with annotations
- Generating dynamic proxies
Second, reflection related classes
- Java.lang. Class: Represents a Class
- Java. Lang. Reflect. Method: on behalf of the class of methods
- Java.lang.reflect. Field: Represents a member variable of the class
- Java. Lang. Reflect. Constructor: on behalf of the class Constructor
Third, Class Class
Class is a Class that describes a Class
You can have class object types class, Interface, [], enum, annotation, primitive data types, void
Class loading and ClassLoader
1. Class loading
- Load: Reads the class file into memory and creates a java.lang. class object. This is done by the class loader
- Link Link: Merges the binary data of the class into the JRE
- Initialize: The JVM is responsible for initializing classes, calling the class constructor (Clint ()) (which initializes class information, not object information), and initializing the parent class if it finds that the parent class has not been initialized
JVM class loading mechanism
-
Full responsibility: When a Class loads a Class, other classes that that Class depends on and references are also loaded by the Class loader
-
Parent delegate: When a Class is loaded, the parent Class loader first loads the Class, and then attempts to load the Class from its own classpath.
-
Caching mechanism: Ensures that all loaded classes are cached. When used again, binary data is read from the cache and converted to Class objects if it does not exist.
2. When is the class initialized
- Active reference to a class (initialization must occur)
- Initialize the main method when the VM starts
- new
- Call class static members {final excepted} and methods
- It’s reflected
- Initializes the parent of an initializing class before it is initialized
- A passive reference to a class (class initialization does not occur)
- Accessing a static domain
- An array defines a reference to a class
- Constants enter the constant pool at the link stage
Class loaders
-
Class loading is used to load the bytecode content of the class file into memory, convert the static data into a method area runtime data structure, and then generate a java.lang. class object of this class in the heap as a class data access point in the method area
-
Class cache: Once a class is loaded, it remains loaded (cached) for a while, but can be reclaimed by JVM garbage collection.
4.ClassLoader
Class loaders are used to load classes into memory
// Get the system class loader
ClassLoader classloader = ClassLoader.getSystemClassLoader();
// Get the parent class loader of the system class loader, extending the class loaderclassloader = classloader.getParent(); .// Tests the classloader for the current class
classloader = Class.forName("exer2.ClassloaderTest").getClassLoader();
GetResourceAsStream (String STR) : Gets the input stream of the specified file in the classpath
InputStream in = null;
in = this.getClass().getClassLoader.getReasourceAsStream("exer2\\test.properties");
Copy the code
5. Create objects for the runtime class
What can you do with a runtime Class object?
- Create an object of the Class by calling newInstance() on the Class object (the Class must have a parameterless constructor and sufficient access rights).
- The parameterized constructor creates an object:
// Get the Class object based on the full Class name
String name = "atgu.java.Person";
Class clazz null;
clazz = Class.forName(name);
// Call the Constructor for the specified argument structure, generating an instance of Constructor
Constructor con = clazz.getConstructor(String.class,Integer.class);
// Create objects of the corresponding class from the Constructor instance and initialize the properties
Person p = (Person)con.newInstance("Peter".20);
Copy the code
6. Get the complete structure of the runtime class
Interface @@class
[] interfaces () 2. @@public Class
getSuperclass() 3. Constructor[] getConstructors() : Constructor[] getDeclaredConstructors(): All constructors 4 All methods @@method [] getDeclaredMethods(): all methods of a class or interface @@method [] getMethods(): return public Method @@@getreTurnType (): return all values @@@getExceptionTypes(): Get all parameters @@@getModiFIERS (): Get exception information 5 All fields @@public Field[] getFields(): all fields @@public Field[] getDeclaredFields(): all fields of the class or interface @@@getType (): Gets the Field’s property type @@@getName(): Returns the Field’s name Generic correlation getGenericSuperclass(): Gets the parent generic type 8. @@package getPackage()
7. Invoke the specified structure of the runtime class
1. Invoke the specified method
- getMethod(String name,Class… paramenterType)
- Object invoke(Object obj,Object[] args)
- In the case of a private method, the serAccessible (True) method (which initiates and disables Java’s access security checks) of the method object is displayed before invoking invoke.
2. Invoke the specified property
- GetField (String name)
- GetDeclaredField (String name)
In the Filed
- Get (Object obj) : Gets the content of the Field property on the specified Object obj
- Set (Object obj, Object value) : Sets the property content of this Field on Object obj
8. Reflection applications: dynamic proxies
Dynamic proxy: Clients invoke methods of other objects through proxy classes and dynamically create proxy objects of the target class as needed at run time.
Application: debugging, remote method call RMI
Advantages over static proxies: all methods in the abstract role (interface) are moved to a centralized method of the calling handler.
Java dynamic proxy API
- Proxy: is the parent of all dynamic Proxy classes. Generate implementation classes for other classes through this class
- Static Class getProxyClass(ClassLoader loader,Class… Interfces): create dynamic proxy corresponding to the class class – Object newProxyInstance (ClassLoader loader, class
[] interfaces, InvocationHandler h) : create a dynamic proxy object directly
Dynamic Proxy step 1. Create an InvocationHandler class that must implement the Invoke method to perform the specific operations of the proxy
public Object invokeObject theProxy(Object theProxy),Method Method (the Method to call),Object[] Paraments)throws Throwable{ Object retval = method.invoke(targetObj,params); . }Copy the code
2. Create proxied classes and interfaces
RealSubject implements Subject
Copy the code
3. Use the Proxy static newInstance (ClassLoader loader,Class<? > [] interfaces, InvocationHandler h) to obtain a Subject object
RealSubject target = new RealSubject();
DebugProxy proxy = new DebugProxy(target);
Subject sub = (Subject)Proxy.newProxyInstance(
Subject.calss.getClassLoader(),new Class[]{Subject.class},proxy);
Copy the code
4. Invoke the RealSubject implementation class methods through the Subject proxy
AOP agentA dynamic Proxy is usually generated for a specified target object rather than out of thin air. In AOP, it’s called an AOP proxy. An AOP proxy can replace the target object and contain all the methods of the target object.The methods of an AOP proxy can insert some generic processing before and after the execution of the target method.
Knowledge map
View online:Java reflection Reflect