JAVA Advanced - Dynamic Proxy

Table of contents

1. What is a dynamic proxy?

 Second, how to create a proxy object for a Java object?

3. Two common dynamic proxy methods

1. Interface-based dynamic proxy

2. Class-based dynamic proxy 


1. What is a dynamic proxy?

How to add new functions to the original code?

 We can use intrusive modification  to directly operate:

 But in future development, this operation is very bad, so we introduce dynamic proxy  :

  • Dynamic proxy is a technology that creates a proxy object of the target object and enhances the functionality of the methods in the target object during program runtime. In the process of generating the proxy object, the target object remains unchanged, and the method in the proxy object is an enhanced method of the target object method. It can be understood as the dynamic interception of methods in objects during runtime, and functional operations are performed before and after the interception method.
  • A dynamic agent is like an intermediary company, making preparations in advance. Features: Add extra functionality to the code without intrusion.

The appearance of the proxy is the method of the object to be proxied, so how does Java guarantee the appearance of the proxy:

  • Through the interface guarantee, the subsequent objects and proxies need to implement the same interface, and the interface contains all the methods of the proxied.

 Second, how to create a proxy object for a Java object?

  • java.lang.reflect.Proxy class: Provides methods for generating proxy objects for objects

public class ProxyUtil {
	// 给对象创建代理
	public static Star createProxy(BigStar bigstar) {
		Star star = Proxy.newProxyInstance(
				//参数一:用于指定用哪个类加载容器,去加载生成的代理类
				ProxyUtil.class.getClassLoader(),
				//参数二:指定接口,这些接口用于指定生成的代理长什么,也就是有哪些方法
				new Class[] {Star.class},
				//参数三:用来指定生成的代理对象要干什么事情
				new InvocationHandler() {
					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						// TODO Auto-generated method stub
						return null;
					}
				}
	};return star;
}}

3. Two common dynamic proxy methods

1. Interface-based dynamic proxy

  • Provider: JDK
  • Create a proxy object using the official JDK Proxy class
  • Note: The target object of the proxy must implement the interface
public static Object getObject(final Object obj){
        Object proxyInstance = Proxy.newProxyInstance(
                 obj.getClass().getClassLoader(), 
                 obj.getClass().getInterfaces(), 
                 new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) 
                     throws Throwable {
                //方法执行前
                long startTime = System.currentTimeMillis();

                Object result = method.invoke(obj, args);//执行方法的调用

                //方法执行后
                long endTime = System.currentTimeMillis();
                SimpleDateFormat sdf = new SimpleDateFormat();
                System.out.printf(String.format("方法执行结束时间:方法执行耗时:"
          , method.getName()), sdf.format(endTime), endTime - startTime);
                return result;
            }
        });
        return proxyInstance;
}

2. Class-based dynamic proxy 

  • Provider: third-party CGLib
  • Create a proxy object using CGLib's Enhancer class
  • Note: If an asmxxxx exception is reported, the asm.jar package needs to be imported
public static Object getObjectByCGLib(final Object obj){
        Object proxyObj = Enhancer.create(
                          obj.getClass(),
                    new MethodInterceptor() {
        public Object intercept(Object o, Method method, 
                Object[] objects, MethodProxy methodProxy) throws Throwable {
                //方法执行前
                long startTime = System.currentTimeMillis();

                Object invokeObject = method.invoke(obj, objects);//执行方法的调用

                //方法执行后
                long endTime = System.currentTimeMillis();
                SimpleDateFormat sdf = new SimpleDateFormat();
                System.out.printf(String.format("方法执行结束时间:方法执行耗时:"
              , method.getName()), sdf.format(endTime), endTime - startTime);
                return invokeObject;
            }
        });
        return proxyObj;
    }

Guess you like

Origin blog.csdn.net/hdakj22/article/details/129667961