黑马程序员技术交流社区
标题:
动态代理!类型转换!
[打印本页]
作者:
杨志
时间:
2012-5-6 13:13
标题:
动态代理!类型转换!
本帖最后由 杨志 于 2012-7-30 13:25 编辑
本人自己刚写一个个动态代理的源代码。
public static void main(String[] args) {
Person person = new Person();
MyProxy myProxy = new MyProxy(person);
// System.out.println(Proxy.newProxyInstance(Person.class.getClassLoader(),Person.class.getInterfaces(),
// myProxy));
Human personProxy = (Human) Proxy.newProxyInstance(
Person.class.getClassLoader(), Person.class.getInterfaces(),
myProxy);
// 以下代码则会报错。
// Person personProxy =
// (Person)Proxy.newProxyInstance(Person.class.getClassLoader(),Person.class.getInterfaces(),
// myProxy);
personProxy.save();
}
复制代码
其中的Person是Human的实现类。
原因是;为什么下面的用Person强制转换会有错。必须去用它的父接口Human转换,就能通过。
其中代理类确实是Person类。求解答!
谢谢!
作者:
姚鑫
时间:
2012-5-6 13:43
1333676113_1211.jpg
(24.9 KB, 下载次数: 31)
下载附件
2012-5-6 13:34 上传
如图,在你的程序中,Human是接口,Person是目标类,personProxy是代理类。
可见,代理类和目标类没有继承的关系,是兄弟的关系。
Human是父亲,他有两个儿子,Person和personProxy,Person能做的事,personProxy也能做,并且还能多做些而外的事,所以personProxy能代理Person。
如果让儿子之间能强转,那就乱辈了。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2