A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 杨文宇 中级黑马   /  2012-8-4 00:39  /  1259 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. package Proxy;

  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5. import java.util.ArrayList;
  6. import java.util.Collection;

  7. public class Test {
  8. public static void main(String[] args) {
  9. final ArrayList arr = new ArrayList();
  10. Test t = new Test();
  11. System.out.println(t.getProxy(arr));
  12. //System.out.println(t.getProxy(arr).getClass().getName());
  13. }
  14. public Object getProxy(final Collection arr){
  15. Object proxy = Proxy.newProxyInstance(Collection.class.getClassLoader(),
  16. Collection.class.getInterfaces(), new InvocationHandler(){
  17. @Override
  18. public Object invoke(Object proxy, Method method, Object[] args)
  19. throws Throwable {
  20. System.out.println("调用代理");
  21. Object reVal = method.invoke(arr, args);
  22. return reVal;
  23. }
  24. });

  25. return proxy;
  26. }
  27. }
复制代码
System.out.println(t.getProxy(arr));//为什么这个调用了invoke。
//System.out.println(t.getProxy(arr).getClass().getName());//这里却没有调用invoke,还有哪些方法是不用调用invoke的。

4 个回复

倒序浏览
// 这里其实是调用了代理对象的toString()方法
System.out.println(t.getProxy(arr));
// 这里调用了代理对象的getClass()方法
System.out.println(t.getProxy(arr).getClass().getName());

关于对你的疑惑的解答:
调用代理对象的从Object继承的hashCode(),equals(Object obj),toStirng()这几个方法时,
代理对象会将调用请求转发InvocationHandler对象的invoke方法
对于其它方法,则不转发调用请求,在代理类内部有自己的实现
getClass()方法正好就是代理类内部自己实现的,所以 invoke 没有运行

回复 使用道具 举报
王志明 发表于 2012-8-4 01:11
// 这里其实是调用了代理对象的toString()方法
System.out.println(t.getProxy(arr));// 这里调用了代理对 ...

还在吗?刚才那个问题我弄懂了。
Proxy.newProxyInstance(Collection.class.getClassLoader(),Collection.class.getInterfaces()
这两个参数有什么用的?
回复 使用道具 举报
杨文宇 发表于 2012-8-4 01:25
还在吗?刚才那个问题我弄懂了。
Proxy.newProxyInstance(Collection.class.getClassLoader(),Collection ...

参数:
第一个--->loader - 定义代理类的类加载器
第二个--->interfaces - 代理类要实现的接口列表
第三个--->h - 指派方法调用的调用处理程序
返回:
一个带有代理类的指定调用处理程序的代理实例,它由指定的类加载器定义,并实现指定的接口

回复 使用道具 举报
王志明 发表于 2012-8-4 01:32
参数:
第一个--->loader - 定义代理类的类加载器
第二个--->interfaces - 代理类要实现的接口列表

第一个--->loader - 定义代理类的类加载器
不是,我感觉定义这个类加载器没啥作用啊?
第二个--->interfaces - 代理类要实现的接口列表
同上。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马