首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

运用JDK动态代理及CGLIB动态代理的方法

2012-11-01 
使用JDK动态代理及CGLIB动态代理的方法一、使用JDK创建实现目标对象所有接口的一个代理对象。public class C

使用JDK动态代理及CGLIB动态代理的方法

一、使用JDK创建实现目标对象所有接口的一个代理对象。

public class CGlibProxyFactory implements  MethodInterceptor{private Object targetObject;public Object createProxyInstance(Object targetObject){this.targetObject = targetObject;Enhancer enhancer = new Enhancer();/**产生目标类的子类,在该子类中会覆盖所有非final修饰符的方法*/enhancer.setSuperclass(this.targetObject.getClass());/**设置回调方法的对象(回调intercept方法)**/enhancer.setCallback(this);return enhancer.create();}@Override/** * proxy  代理对象  * method 拦截的方法 * args 方法的输入参数  methodProxy 方法的代理对象 */public Object intercept(Object proxy, Method method, Object[] args,MethodProxy methodProxy) throws Throwable {PersonServiceBean personServiceBean = (PersonServiceBean)this.targetObject;Object result = null;/**代理对象将方法的访问委派给目标对象**/if(personServiceBean.getUser() != null){result = method.invoke(this.targetObject, args);}// TODO Auto-generated method stubreturn null;}}
?

?

热点排行