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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 杨志 高级黑马   /  2012-5-6 13:13  /  1896 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 杨志 于 2012-7-30 13:25 编辑

本人自己刚写一个个动态代理的源代码。
  1. public static void main(String[] args) {

  2.                 Person person = new Person();

  3.                 MyProxy myProxy = new MyProxy(person);

  4.                 // System.out.println(Proxy.newProxyInstance(Person.class.getClassLoader(),Person.class.getInterfaces(),
  5.                 // myProxy));

  6.                 Human personProxy = (Human) Proxy.newProxyInstance(
  7.                                 Person.class.getClassLoader(), Person.class.getInterfaces(),
  8.                                 myProxy);
  9.                 // 以下代码则会报错。
  10.                 // Person personProxy =
  11.                 // (Person)Proxy.newProxyInstance(Person.class.getClassLoader(),Person.class.getInterfaces(),
  12.                 // myProxy);

  13.                 personProxy.save();
  14.         }
复制代码
其中的Person是Human的实现类。
原因是;为什么下面的用Person强制转换会有错。必须去用它的父接口Human转换,就能通过。
其中代理类确实是Person类。求解答!
谢谢!

1 个回复

倒序浏览

如图,在你的程序中,Human是接口,Person是目标类,personProxy是代理类。
可见,代理类和目标类没有继承的关系,是兄弟的关系。
Human是父亲,他有两个儿子,Person和personProxy,Person能做的事,personProxy也能做,并且还能多做些而外的事,所以personProxy能代理Person。
如果让儿子之间能强转,那就乱辈了。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马