前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >InvocationHandler中invoke方法中的第一个参数proxy的用途

InvocationHandler中invoke方法中的第一个参数proxy的用途

作者头像
yaphetsfang
发布2020-07-30 14:29:03
1.3K0
发布2020-07-30 14:29:03
举报
文章被收录于专栏:yaphetsfang

最近在研究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并不是代理对象。

下面看源代码,完整代码:http://paste.ubuntu.com/26104595/

接口:

代码语言:javascript
复制
 
private interface Account {
 
public Account deposit (double value);
 
public double getBalance ();
 
}

Handler:

代码语言:javascript
复制
 
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;
 
}
 
}

使用:

代码语言:javascript
复制
 
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。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-07-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档