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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 血马雄风 中级黑马   /  2015-8-28 10:07  /  242 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


技术要求:将系统功(例如:日记、统计等信息)能添加代理对象上

技术要点:


//获取proxy对象,将系统功能添加到代理中
private static Object getProxy(final Object proxied, final Advice advice){
    return Proxy.newProxyInstance(
                      proxied.getClass().getClassLoader(),
                      proxied.getClass().getInterfaces(),
                      new InvocationHandler(){
                          public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
                              //....
                              advice.beforeMethod();
                              Object retVal = method.invoke(proxiec, args);
                              advice.afterMethod();
                              //....
                              return retVal;
                          }
                      });  
}

//系统功能
public interface Advice{
    void beforeMethod(Method method);
    void afterMethod(Method method);
}

public class MyAdvice emplements Advice{
    public void beforeMethod(Method method){
        System.out.println(method.getName() + "-Advice-" + "beforeMethod");      
    }

    public void afterMethod(Method method){{
        System.out.println(method.getName() + "-Advice-" + "afterMethod");        
    }
}


//main
ArrayList proxied = new ArrayList();
Collection collectionProxy = (Collection)getProxy(proxied, new Advice());
collectionProxy.add("aaa");
collectionProxy.add("ccc");
collectionProxy.add("bbb");

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马