动态代理

tech2025-07-28  7

文章目录

JDK动态代理ProxyInvocationHandler调用 CGLIBProxyInterceptor调用

JDK动态代理

通过多态调用,需要有接口

ProxyInvocationHandler

@AllArgsConstructor public class ProxyInvocationHandler implements InvocationHandler { //实际调用的实现类,用多态调用 private ServerInterface serverInterface; @Override //代理类执行方法会被拦截进入invoke() public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //调用实现类的方法 method.invoke(serverInterface,args); return null; } }

调用

public void function() { /*public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h) loader 类加载器 interfaces 要实现的接口 h 处理程序,进入的方法会调用InvocationHandler.invoke() */ ServerInterface server = (ServerInterface) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[]{ServerInterface.class}, new ProxyInvocationHandler(new ServerImpl())); server.function(); }

CGLIB

ProxyInterceptor

public class ProxyInterceptor implements MethodInterceptor { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { //调用实现类的方法 methodProxy.invokeSuper(o,objects); return null; } }

调用

public void function() { Enhancer enhancer = new Enhancer(); //要代理的类 enhancer.setSuperclass(Server.class); //拦截器 enhancer.setCallback(new ProxyInterceptor()); //代理对象 Server server = (Server) enhancer.create(); server.function(); }
最新回复(0)