最近在研究Java的动态代理时对InvocationHandler中invoke方法中的第一个参数一直不理解它的用处,某度搜索也搜不出结果,最后终于在stackoverflow上找到了答案。
这是原文的链接:http://stackoverflow.com/questions/22930195/understanding-proxy-arguments-of-the-invoke-method-of-java-lang-reflect-invoca
原文对这个参数的解释是:
1. 可以使用反射获取代理对象的信息(也就是proxy.getClass().getName())。
2. 可以将代理对象返回以进行连续调用,这就是proxy存在的目的。因为this并不是代理对象,
下面看源代码
接口:
- private interface Account {
- public Account deposit (double value);
- public double getBalance ();
- }
Handler:
- private class ExampleInvocationHandler implements InvocationHandler {
- private double balance;
- @Override
- public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {
- // simplified method checks, would need to check the parameter count and types too
- if ("deposit".equals(method.getName())) {
- Double value = (Double) args[0];
- System.out.println("deposit: " + value);
- balance += value;
- return proxy; // here we use the proxy to return 'this'
- }
- if ("getBalance".equals(method.getName())) {
- return balance;
- }
- return null;
- }
- }
使用:
- Account account = (Account) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] {Account.class, Serializable.class},
- new ExampleInvocationHandler());
- // method chaining for the win!
- account.deposit(5000).deposit(4000).deposit(-2500);
- System.out.println("Balance: " + account.getBalance());
我们看到如果返回proxy的话可以对该代理对象进行连续调用
那为什么不返回this,而是返回proxy对象呢?
因为this对象的类型是ExampleInvocationHandler,而不是代理类$Proxy0
除此之外,不返回代理对象的话,还能返回其他信息,如balance。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决