动态代理 Proxy InvocationHandler

能够在核心业务方法前后做一些你所想做的辅助工作,如log日志,安全机制等等。

import java.lang.reflect.*;

public interface Business{public void do();}

public class BusinessImp implements Business{public void do(){。。。}}

public class MyInvocationHandler implements InvocationHandler{

  private Object target = null;

  public MyInvocationHandler(Object target){this.target = target;}

@Override

  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{

    调用核心业务方法前操作

    Object result = method.invoke(target, args);

    调用核心业务方法后操作

    return result;//返回代理对象

  }

}

public class Test{

  BusinessImp busi = new BusinessImp();//被代理对象

  MyInvocationHandler handler = new MyInvocationHandler(busi);

  Business proxy = (Business)Proxy.newProxyInstance(busi.getClass().getClassLoader(), busi.getClass().getInterface(),handler);

  proxy.do();//调用do时会调用handler的invoke方法

}

 

posted on 2017-08-28 16:48  zawjdbb  阅读(104)  评论(0编辑  收藏  举报

导航