cglib实现无接口代理? 使用情况:有时候我们需要为一个类建立代理对象,当执行原类的某种方法时,进行某些操
cglib实现无接口代理
? 使用情况:有时候我们需要为一个类建立代理对象,当执行原类的某种方法时,进行某些操作,但是这要求我们原来的类实现某种接口。如果原来的类没有实现任何的接口怎么实现代理哪?现在我们可以利用Cglib为任何的类产生代理对象,不管原来的类有没有实现接口,甚至我们可以使代理对象动态的实现任意接口。
? 例子:
???? 1、产生带拦截器的代理对象。
???? 2、产生带拦截器和继承接口的代理对象。
???? 3、产生带拦截器和拦截器过滤器的代理对象。
? 包里的内容:
?????案例,依赖包。
?
at com.muzi.util.reflect.CglibTest$$EnhancerByCGLIB$$ddc15b7a.CGLIB$getIntValue$7(<generated>)
at com.muzi.util.reflect.CglibTest$$EnhancerByCGLIB$$ddc15b7a$$FastClassByCGLIB$$d4e392b.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:215)
at com.muzi.util.reflect.MethodInterceptorImpl1.intercept(MethodInterceptorImpl1.java:21)
at com.muzi.util.reflect.CglibTest$$EnhancerByCGLIB$$ddc15b7a.getIntValue(<generated>)
at com.muzi.util.reflect.CglibTest.main(CglibTest.java:34)at com.muzi.util.reflect.CglibTest$$EnhancerByCGLIB$$ddc15b7a.CGLIB$getIntValue$7(<generated>)
at com.muzi.util.reflect.CglibTest$$EnhancerByCGLIB$$ddc15b7a$$FastClassByCGLIB$$d4e392b.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:215)
at com.muzi.util.reflect.MethodInterceptorImpl1.intercept(MethodInterceptorImpl1.java:21)
at com.muzi.util.reflect.CglibTest$$EnhancerByCGLIB$$ddc15b7a.getIntValue(<generated>)
at com.muzi.util.reflect.CglibTest.main(CglibTest.java:34)
因为CglibTest类并没有getIntValue方法所以会报错,所以还要自CglibTest类中加入getIntValue方法,比如
public int getIntValue(){
return 1;
}。 ,不错
,不错
at com.muzi.util.reflect.CglibTest$$EnhancerByCGLIB$$ddc15b7a.CGLIB$getIntValue$7(<generated>)
at com.muzi.util.reflect.CglibTest$$EnhancerByCGLIB$$ddc15b7a$$FastClassByCGLIB$$d4e392b.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:215)
at com.muzi.util.reflect.MethodInterceptorImpl1.intercept(MethodInterceptorImpl1.java:21)
at com.muzi.util.reflect.CglibTest$$EnhancerByCGLIB$$ddc15b7a.getIntValue(<generated>)
at com.muzi.util.reflect.CglibTest.main(CglibTest.java:34)
因为CglibTest类并没有getIntValue方法所以会报错,所以还要自CglibTest类中加入getIntValue方法,比如
public int getIntValue(){
return 1;
}。
我觉得CGLIB的真正威力就是动态代理吧,即使原来的对象不具备某接口中的方法也是可以的,因为CGLIB可以在运行时修改类的定义,个人觉得还是你这个例子做的不是很到位。 7 楼 bryande 2011-02-16 建议看看Spring拦截器的实现,就是用cglib和java中的proxy类