黑马程序员技术交流社区

标题: 动态代理!类型转换! [打印本页]

作者: 杨志    时间: 2012-5-6 13:13
标题: 动态代理!类型转换!
本帖最后由 杨志 于 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类。求解答!
谢谢!
作者: 姚鑫    时间: 2012-5-6 13:43

如图,在你的程序中,Human是接口,Person是目标类,personProxy是代理类。
可见,代理类和目标类没有继承的关系,是兄弟的关系。
Human是父亲,他有两个儿子,Person和personProxy,Person能做的事,personProxy也能做,并且还能多做些而外的事,所以personProxy能代理Person。
如果让儿子之间能强转,那就乱辈了。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2