Detailed Explanation of JAVA's Dynamic Proxy


Preface

Dynamic proxies provide a flexible and non-intrusive way to customize and extend the behavior of objects. It plays an important role in code reuse, decoupling and business logic separation, performance optimization, and system architecture.

Enhance the functionality of an object : With dynamic proxies, its methods can be enhanced or additional behavior can be added without modifying the original object. Some operations can be performed before and after method execution, such as logging, performance monitoring, transaction management, etc.

Decoupling and separation of business logic : Dynamic proxies can decouple specific operations of objects from business logic, making the code more modular and maintainable. Proxy objects can be responsible for handling some common cross-cutting concerns, while business objects can focus on core business logic.

Implement lazy loading : Through dynamic proxy, objects can be loaded lazily, and objects will be created and initialized only when they are actually needed, thereby improving performance and resource utilization efficiency.

Implementing remote method calls : Dynamic proxies can be used to implement remote method calls (RPC) and service proxies in distributed systems. The client calls the remote service through the proxy object and hides the details of the underlying network communication.

Implementing AOP programming : Dynamic proxies are the basis for implementing aspect-oriented programming (AOP). Through proxy objects, cross-cutting concerns (such as logging, transactions, security) can be decoupled from business logic, providing a higher level of modularity and reusability.


1. What is dynamics?

Dynamic proxy is a design pattern that allows proxy objects to be created at runtime and method calls to be redirected to a different real object. It enables us to add or change the behavior of an object without modifying existing code.

2. Usage steps

1. Import the corresponding package

In Java, you can use Java's reflection mechanism to implement dynamic proxies. Java provides java.lang.reflect.Proxy class and java.lang.reflect.InvocationHandler interface to implement dynamic proxy.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

2. Define the interface

// 定义接口
interface UserService {
    
    
    void addUser(String username);
}

3. Define the interface implementation class

// 实现接口的具体类
class UserServiceImpl implements UserService {
    
    
    public void addUser(String username) {
    
    
        System.out.println("添加用户:" + username);
    }
}

4. Implement the InvocationHandler interface

// 实现InvocationHandler接口
class MyInvocationHandler implements InvocationHandler {
    
    
	// 声明一个私有变量
    private Object target;

	// 构造函数
    public MyInvocationHandler(Object target) {
    
    
        this.target = target;
    }

	//  实现InvocationHandler接口的invoke方法,该方法在代理对象调用方法时被触发。
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
        System.out.println("动态代理前置操作");
        Object result = method.invoke(target, args);
        System.out.println("动态代理后置操作");
        return result;
    }
}

This code implements the InvocationHandler interface, which is a key part of implementing dynamic proxy.

5. Implement proxy

public class DynamicProxyExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建目标对象
        UserService userService = new UserServiceImpl();

        // 创建InvocationHandler实例
        MyInvocationHandler handler = new MyInvocationHandler(userService);

        // 创建动态代理对象
        UserService proxy = (UserService) Proxy.newProxyInstance(
                userService.getClass().getClassLoader(),
                userService.getClass().getInterfaces(),
                handler
        );

        // 通过代理对象调用方法
        proxy.addUser("Alice");
    }
}

3. Overall Example

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

// 定义接口
interface UserService {
    
    
    void addUser(String username);
}

// 实现接口的具体类
class UserServiceImpl implements UserService {
    
    
    public void addUser(String username) {
    
    
        System.out.println("添加用户:" + username);
    }
}

// 实现InvocationHandler接口
class MyInvocationHandler implements InvocationHandler {
    
    
    private Object target;

    public MyInvocationHandler(Object target) {
    
    
        this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
        System.out.println("动态代理前置操作");
        Object result = method.invoke(target, args);
        System.out.println("动态代理后置操作");
        return result;
    }
}

public class DynamicProxyExample {
    
    
    public static void main(String[] args) {
    
    
        // 创建目标对象
        UserService userService = new UserServiceImpl();

        // 创建InvocationHandler实例
        MyInvocationHandler handler = new MyInvocationHandler(userService);

        // 创建动态代理对象
        UserService proxy = (UserService) Proxy.newProxyInstance(
                userService.getClass().getClassLoader(),
                userService.getClass().getInterfaces(),
                handler
        );

        // 通过代理对象调用方法
        proxy.addUser("Alice");
    }
}

4. Output results

动态代理前置操作
添加用户:Alice
动态代理后置操作

Summarize

Dynamic proxies are useful in many places, such as logging, performance monitoring, permission verification, etc. This dynamic proxy design pattern allows us to customize and extend the behavior of objects in a non-intrusive way, providing higher flexibility and maintainability.

Guess you like

Origin blog.csdn.net/biyn9/article/details/131352424
Recommended