Dynamic proxy implementation principle

1. Dynamic proxy

First of all, dynamic proxy is an implementation method of proxy mode. In addition to dynamic proxy, proxy mode also has static proxy. However, static proxy can determine the execution object of the class at compile time, while dynamic proxy can only determine the execution object at runtime. who. The proxy can be regarded as an encapsulation of the final call target. We can call the target class by operating the proxy object, so that the caller and the target object can be decoupled.

There are many application scenarios for dynamic proxy, the most common ones are AOP implementation, RPC remote calling, Java annotation object acquisition, logging framework, global exception handling, transaction processing, etc. There are many implementations of dynamic proxy, but JDK dynamic proxy is a very important one.

The agent pattern is a commonly used Java design pattern. Its characteristic is that the agent class and the delegate class have the same interface. The agent class is mainly responsible for preprocessing messages for the delegate class, filtering messages, forwarding messages to the delegate class, and processing messages afterwards. There is usually an association between a proxy class and a delegate class. An object of a proxy class is associated with an object of a delegate class. The object of the proxy class itself does not actually implement the service, but by calling the relevant methods of the object of the delegate class. Provide specific services. To put it simply, when we access the actual object, we access it through the proxy object. The proxy mode introduces a certain degree of indirection when accessing the actual object, because this indirection can be used for a variety of purposes.

JDK dynamic proxy

First, let’s take a look at the execution process of dynamic proxy

 In JDK dynamic proxy, the class that implements InvocationHandler can be regarded as a proxy class (because a class is also an object, so in order to describe the relationship above, we described the proxy class as a proxy object). JDK dynamic proxy is centered around the proxy class that implements InvocationHandler. For example, the following is an implementation class of InvocationHandler, which is also a proxy class.

 1: InvocationHandler interface

There is only one method in the interface: invoke()
The function that your proxy class wants to complete is written in invoke()

Functions that the proxy class needs to complete:

Call the method of the target class
Function enhancement, add functions and method prototype when the target method is called
Object proxy: proxy object created by jdk , no assignment required
Method method: Method in the target class
Object[] args: Parameters of the method in the target class
public Object invoke(Object proxy, Method method, Object[] args)

2: Method class

Through Method, you can execute the method of a certain target class

3: proxy class

is the core class. Use the static method newProxyInstance() to create a proxy object.
Method prototype:
ClassLoader loader: Class loader, Responsible for loading objects into memory (need to use the class loader of the target object)
Class<?>[] interfaces: the interface implemented by the target object InvocationHandler h: the proxy class we wrote ourselves needs to be implemented The function return value is the proxy object public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,InvocationHandler h)

Implementation steps of dynamic proxy

  • Create an interface and define the functions to be completed by the target class
public interface BookService {
    void sing(int a,double b);

    void dance();

    void rap();
}
public class CXK implements BookService {

    @Override
    public void sing(int a,double b) {
        System.out.println("唱歌"+a+"---"+b);
    }

    @Override
    public void dance() {
        System.out.println("跳舞");
    }

    @Override
    public void rap() {
        System.out.println("rap");
    }
}
  • Use the newProxyInstance() method of the proxy class to create a proxy object and convert the return value into an interface type
public class Test01 {
    public static void main(String[] args) {
        BookService cxk = new CXK();

        BookService jjr = (BookService) Proxy.newProxyInstance(CXK.class.getClassLoader(), CXK.class.getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                Object result = null;
                String name = method.getName();
                result=method.invoke(cxk,args);
                return result;
            }
        });
        jjr.sing(5,33.0);
        jjr.dance();
        jjr.rap();
    }
}

operation result:

Guess you like

Origin blog.csdn.net/weixin_69036336/article/details/129823590