JDK动态代理
@Test public void testProxy(){ //创建InvocationHandler对象 MyInvocationHandler handler = new MyInvocationHandler(new ProxyServiceImpl()); //调用JDK的代理方法 ProxyService newProxyInstance = (ProxyService)Proxy.newProxyInstance( proxyServiceImpl.getClass().getClassLoader(), proxyServiceImpl.getClass().getInterfaces(), handler); newProxyInstance.add(); }
分析:JDK动态代理需要执行
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
其中参数含义:
loader – the class loader to define the proxy class(用于定义代理类的类加载器)
interfaces – the list of interfaces for the proxy class to implement(代理类要实现的接口列表)
h – the invocation handler to dispatch method invocations to(将方法调用分派到的调用处理程序,即自己定义的handler处理对象)
handler如下:(需要实现InvocationHandler接口),在重写的invoke方法中添加代理方法执行前后的逻辑处理。
public class MyInvocationHandler implements InvocationHandler { //被代理的对象 private ProxyService proxyService; public MyInvocationHandler(ProxyService proxyService) { this.proxyService = proxyService; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("add()执行前。。。。"); //真正执行的方法 Object invoke = method.invoke(proxyService, args); System.out.println("add()执行后。。。。"); return invoke; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能