1.静态代理
public interface Company { void cooperation(); }
public class Start implements Company { public void cooperation() { System.out.println("1"); } }
代理类
public class Agent implements Company { private Company company; public Agent(Company company) { this.company = company; } public void cooperation() { System.out.println("===before==="); company.cooperation(); System.out.println("===after==="); } }
调用
Company company=new Start(); Agent agent=new Agent(company); agent.cooperation();
2.动态代理 jdk实现
public class JdkProxy implements InvocationHandler { private Company company; public JdkProxy(Company company) { this.company = company; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("=====before====="); Object result= method.invoke(company,args); System.out.println("=====after====="); return result; } }
调用
动态生成代理对象需要调用JDK中的java.lang.reflect.Proxy类的newProxyInstance方法,这个方法需要三个参数:
@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,]Class[] interfaces,InvocationHandler h)
ClassLoader loader:类加载器,用来加载目标对象类,因为是在运行时获得目标对象,所以肯定需要用到反射。
Class[] interfaces:目标对象类实现的接口集合,这些接口中定义目标对象可以执行的方法。
InvocationHandler h:这个参数代表的是动态代理对象在调用方法的时候,会将方法转发到哪一个invocationHandler对象身上,InvocationHandler是个接口,
需要自己实现它,然后定义自己的动态代理执行方法。
创建包含动态代理对象具体执行方法的实现类。
Company company = new Start(); JdkProxy jdkProxy = new JdkProxy(company); Company proxy = (Company) Proxy.newProxyInstance(jdkProxy.getClass().getClassLoader(), company.getClass().getInterfaces(), jdkProxy); proxy.cooperation();
3.cglib 动态代理
public class AloneStart { /** 合作 */ public void cooperation() { System.out.println("is show time"); } }
代理类
package com.jd.xq.proxy; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import java.lang.reflect.Method; /** * @author duanxiaoqiu * @Date 2019-12-18 14:44 **/ public class CglibProxy implements MethodInterceptor { public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("=====before===="); Object result = methodProxy.invokeSuper(o, objects); System.out.println("=====after===="); return result; } }
Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(AloneStart.class); enhancer.setCallback(new CglibProxy()); AloneStart aloneStart = (AloneStart) enhancer.create(); aloneStart.cooperation();
spring aop等