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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© hello_world! 中级黑马   /  2012-10-30 15:28  /  1485 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

这段代码是张孝祥老师将代理时候的代码:
public class ProxyTest {


        public static void main(String[] args) throws Exception{
               
               
                final ArrayList target = new ArrayList();                       
                Collection proxy3 = (Collection)getProxy(target,new MyAdvice());//为什么这里不能直接转换成 ArrayList,我强制转换的结果是出现类型转换异常,为什么?
                proxy3.add("zxx");
                proxy3.add("lhm");
                proxy3.add("bxd");
                System.out.println(proxy3.size());
                System.out.println(proxy3.getClass().getName());
        }

        private static Object getProxy(final Object target,final Advice advice) {
                Object proxy3 = Proxy.newProxyInstance(
                                target.getClass().getClassLoader(),
                                target.getClass().getInterfaces(),
                                new InvocationHandler(){
                               
                                        public Object invoke(Object proxy, Method method, Object[] args)
                                                        throws Throwable {

                                                advice.beforeMethod(method);
                                                Object retVal = method.invoke(target, args);
                                                advice.afterMethod(method);
                                                return retVal;                                               
                                               
                                        }
                                }
                                );
                return proxy3;
        }

}

求高手解答:红色标记的部分。先说我自己的分析,既然返回结果是ArrayList代理的,就应该可以转换成ArrayList,而为什么一定要转换成Collection?


评分

参与人数 1技术分 +1 收起 理由
韩军博 + 1

查看全部评分

2 个回复

倒序浏览
用JDK 中的Proxy 来产生代理的话,目标代理类首先被要求是要有接口的,生成的代理类也是实现了目标类的接口的, 这个类是和目标代理类是平行的,同样都是实现了目标类的接口的,所以你只可以强转成目标类的接口类型,
但是框架中的动态代理都是用了动态生成字节码的方式来生成代理的。

评分

参与人数 1技术分 +1 收起 理由
韩军博 + 1

查看全部评分

回复 使用道具 举报
范贞亮 发表于 2012-10-30 15:40
用JDK 中的Proxy 来产生代理的话,目标代理类首先被要求是要有接口的,生成的代理类也是实现了目标类的接口 ...

嗯,谢谢了:)
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马