Java實現的攔截器

來源:互聯網
上載者:User

標籤:

/**

  * 動態產生一個代理類對象,並綁定被代理類和代理處理器

  *

  * @param business

  * @return 代理類對象

  */

  public Object bind(Object business) {

  this.business = business;

  return Proxy.newProxyInstance(

  //被代理類 的ClassLoader

  business.getClass().getClassLoader(),

  //要被代理 的介面,本方法返回對象會自動聲稱實現了這些介面

  business.getClass().getInterfaces(),

  //代理處理 器對象

  this);

  }

  /**

  * 代理要調用的方法,並在方法調用前後調用連接器的方法.

  *

  * @param proxy  代理類對象

  * @param method 被代理的介面方法

  * @param args   被代理介面方法的參數

  * @return 方法調用返回的結果

  * @throws Throwable

  */

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

  Object result = null;

  interceptor.before();

  result=method.invoke(business,args);

  interceptor.after();

  return null;  //To change body of implemented methods use File | Settings | File Templates.

  }

  }

  三、攔截器:普通的JavaBean,在調用業務方法的之前或者之後會自動攔截並執行自己的 一些方法。

  /**

  * 攔截器

  */

  public class InterceptorClass {

  public void before(){

  System.out.println("攔截器InterceptorClass方法調用:before()!");

  }

  public void after(){

  System.out.println("攔截器InterceptorClass方法調用:after()!");

  }

  }

  四、類比用戶端:執行業務處理的入口。

  /**

  * 用戶端

  */

  public class Client {

  public static void main(String args[]) {

  DynamicProxyHandler handler = new DynamicProxyHandler();

  BusinessInterface business = new BusinessClass();

  BusinessInterface businessProxy = (BusinessInterface) handler.bind(business);

  businessProxy.doSomething();

  }

  }

Java實現的攔截器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.