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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Mr.Hao 中级黑马   /  2014-7-4 10:29  /  1239 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

以下是视频中实现获取代理的方法,
        public static Object getProxy(final Object target, final Advice advice){
                Object proxy = Proxy.newProxyInstance(
                                target.getClass().getClassLoader(),
                                target.getClass().getInterfaces(),
                                new InvocationHandler() {
                                        public Object invoke(Object proxy, Method method, Object[] args)
                                                        throws Throwable {
                                                advice.beforeMethod();
                                                Object obj = method.invoke(target, args);
                                                advice.afterMethod();
                                                return obj;
                                        }
                                });
                return proxy;
        }

其中的这句:public Object invoke(Object proxy, Method method, Object[] args)中的第一个参数Object proxy好像是没有用到呢,到底有什么作用,我把代码稍稍修改了以下,结果还是一样的,就像下面这样

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

评分

参与人数 1技术分 +1 收起 理由
李小然 + 1

查看全部评分

3 个回复

倒序浏览
对于这3个参数的的意思依次是:代理对象,代理对象中的方法和代理方法中的参数,你这样改肯定没问题啊,只不过返回值不一样啦,前者返回的是目标方法的返回值,后者返回的是当前的代理对象啊,也就是你new的这个对象

评分

参与人数 1技术分 +1 收起 理由
李小然 + 1

查看全部评分

回复 使用道具 举报
其实我觉得你还是要理解代理的设计模式,就好理解啦,这里这是接口的形式实现的还有费接口的就要jar包   asm包和cglib他们二者的模式是一样都是定义啦接口来接受处理的被代理的对象然后调用目标达到目的,区别是前者是接口来统一目标,后者是继承实现的
回复 使用道具 举报
还有处理的接口不一样前者是invocationhandler 后者是methodinpreter不知道拼错没有?
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马