java static proxy and dynamic proxy

       The proxy pattern is a common design pattern in java. Its purpose is to provide a proxy for other objects to control access to a real object. Through the middle layer of the proxy class, the direct access to the object of the real delegate class can be effectively controlled, and a custom control strategy can be implemented at the same time. According to the time point when the proxy class is created, it can be divided into static proxy and dynamic proxy.

        1. Static proxy: Generate proxy at compile time, also known as compile time enhancement.

        2. Dynamic proxy: The proxy is generated at runtime, which also becomes a runtime enhancement.

 Dynamic proxies: There are two common implementations of dynamic proxies.

  a.cglib dynamic proxy. The proxy is the class and does not need to implement the interface. The proxy is implemented by subclassing the derived class. The purpose of modifying the class is achieved by dynamically modifying the bytecode at runtime.

  b.jdk dynamic proxy. Implement the invoker method of the class InvocationHandler interface, but note that the proxy is the interface. That is to say, the business class must implement the interface and obtain the proxy object through newProxyInstance in Proxy.

     In the java.lang.reflect package, a Proxy class and an InvocationHandler interface are provided, through which a dynamic proxy of the JDK can be generated.

1. Create your own invocation handler by implementing the InvocationHandler interface

InvocationHandlerImpl 实现了 InvocationHandler 接口,并能实现方法调用从代理类到委托类的分派转发
InvocationHandler handler = new InvocationHandlerImpl(..);

2. Create a dynamic proxy class by specifying a ClassLoader object and a set of interfaces for the Proxy class;

// 通过 Proxy 为包括 Interface 接口在内的一组接口动态创建代理类的类对象
Class clazz = Proxy.getProxyClass(classLoader, new Class[] { Interface.class, ... }); 

3. The constructor of the dynamic proxy class is obtained through the reflection mechanism, and its only parameter type is the interface type of the calling processor;

// 通过反射从生成的类对象获得构造函数对象
Constructor constructor = clazz.getConstructor(new Class[] { InvocationHandler.class });

4. Create a dynamic proxy class instance through the constructor, and call the handler object as a parameter to be passed in during construction.

// 通过构造函数对象创建动态代理类实例
Interface Proxy = (Interface)constructor.newInstance(new Object[] { handler });

In order to simplify the object creation process, the newProxyInstance in the Proxy class encapsulates 2-4 steps, and the creation of the proxy object can be completed in only two steps.

// 通过 Proxy 直接创建动态代理类实例
Interface proxy = (Interface)Proxy.newProxyInstance( classLoader, 
     new Class[] { Interface.class }, 
     handler );

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325160278&siteId=291194637