码迷,mamicode.com
首页 > 编程语言 > 详细

Java实现的拦截器

时间:2015-06-11 22:34:33      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

/**

  * 动态生成一个代理类对象,并绑定被代理类和代理处理器

  *

  * @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实现的拦截器

标签:

原文地址:http://www.cnblogs.com/yjcn/p/4570310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!