Application of Reflection: Dynamic Agent

Posted by clewis4343 on Mon, 14 Feb 2022 19:54:06 +0100

❀ Write before
❀ Blog Home Page: Effortful Naruto
❀ Series Columns: JavaSE Ultra-detailed Summary πŸ˜‹
❀ Welcome to your friends and compliment πŸ‘ follow πŸ”Ž Collection πŸ” Learning together!
❀ If there are any mistakes, please correct them! 🌹

about [Chapter 14 Java Reflection Mechanisms] Java Reflection πŸ”₯ Expansion of

1. Overview

A method in which a client invokes other objects through a proxy class and dynamically creates a proxy object of the target class when the program is run

  1. Usage
    Controlled Remote Method Calls
  2. Benefits over static proxies:
    All methods declared in abstract roles (interfaces) are transferred to a centralized method of the calling processor for processing

πŸ”₯ Related API s

  1. Proxy: An operation class that specializes in agents and is the parent of all dynamic proxy classes
    Dynamic generation of implementation classes for one or more interfaces through this class
  2. Provides static methods for creating dynamic proxy classes and dynamic proxy objects
    ●static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces)
    Create a Class object corresponding to a dynamic proxy class
    ●static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,InvocationHandler h)
    Create a dynamic proxy object directly

2. Principles

Wrap the object with a proxy, then replace the original object with the proxy object, any calls to the original object pass through the proxy. The proxy object determines whether and when method calls will be transferred to the original object

πŸ”₯ Dynamic proxy steps

  1. Create a class that implements the interface InvocationHandler, which must implement the invoke method to complete the proxy's specific operations
public Object invoke(Object theProxy, Method method, Object[] params) throws Throwable{
	Object retval = method.invoke(targetObj, params);
		// Print out the result
		return retval;
	}catch (Exception exc){}

  1. Create proxied classes and interfaces

  1. Static method via Proxy
    newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h)
    Create a Subject interface proxy
RealSubject target = new RealSubject();
// Create a proxy to wrap the original implementation
DebugProxy proxy = new DebugProxy(target);
// Get a reference to the proxy through the Subject interface
Subject sub = (Subject) Proxy.newProxyInstance(
Subject.class.getClassLoader(),new Class[] { Subject.class }, proxy);
  1. Calling a method of a RealSubject implementation class through the Subject proxy
String info = sub.say("Peter", 24);

3. Dynamic Agent and AOP

The AOP proxy replaces the target object, and the AOP proxy contains all the methods of the target object

The methods in the AOP proxy differ from those of the target object:
Methods within an AOP proxy can insert some generic processing before and after executing the target method

A more practical dynamic proxy mechanism is described below:

Improve to

Improved: Code snippets 1, 2, 3, and dark are separated, but snippets 1, 2, 3 are coupled with a specific method A! Ideally, code blocks 1, 2, and 3 can execute method A without having to hard-code a method that directly calls dark code in the program

public class DogUtil{
	public void method1(){
		System.out.println("===== Simulations General Method 1 =====");
	public void method2(){
		System.out.println("===== Simulations General Method 2 =====");
public class MyInvocationHandler implements InvocationHandler{
		// Objects that need to be proxied
		private Object target;
		public void setTarget(Object target){ = target;}
// When all methods of a dynamic proxy object are executed, they are replaced with invoke methods as follows
		public Object invoke(Object proxy, Method method, Object[] args)
				throws Exception{
				DogUtil du = new DogUtil();
				// Execute method1 in the DogUtil object.
				// Execute method method method with target as primary key
				Object result = method.invoke(target , args);
				// Execute method2 in the DogUtil object.
				return result;}}

public class MyProxyFactory{
		// Generate dynamic proxy object for specified target
		public static Object getProxy(Object target)
				throws Exception{
				// Create a MyInvokationHandler object
				MyInvokationHandler handler =
				new MyInvokationHandler();
				// Set the target object for MyInvokationHandler
				// Create and return a dynamic proxy object
		, target.getClass().getInterfaces() , handler);
public class Test{
	public static void main(String[] args)
			throws Exception{
			// Create a raw untingDog object as a target
			Dog target = new HuntingDog();
			// Create dynamic proxy with specified target
			Dog dog = (Dog)MyProxyFactory.getProxy(target);;;

When using Proxy to generate a dynamic proxy, it is not always possible to generate a dynamic proxy from a void
Typically, a dynamic proxy is generated for the specified target object

🎁 Summary: This dynamic agent needs to be carefully considered, unable to read and continue to read
πŸ‘Œ The author is a beginner in Java. If there are any errors in the article, you are welcome to comment on private message corrections and learn together~~
😊 If the article is useful for your little buddies, compliment them πŸ‘ follow πŸ”Ž Collection πŸ” Is my greatest motivation!
🚩 Don't get stuck, don't get as far as a thousand miles, keep going. Welcome to see you again 🌹

Topics: Java AOP Dynamic Proxy