解决过程:
新建了一个 空白工程,写了下CGLIB的简单实现,本以为集成了cglib jar包就行,结果报了一 个classNotFoundException。
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type
at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:184)
at net.sf.cglib.core.KeyFactory.<clinit>(KeyFactory.java:72)
at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:72)
at com.company.refectTest.CglibExample.getProxy(CglibExample.java:15)
at com.company.refectTest.CglibExample.testCGLIBProxy(CglibExample.java:35)
at com.company.Main.main(Main.java:27)
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 6 more
跟踪发现少了一个asm的jar包,这个包主要用来做java字节码操作和分析,由于这个空白工作不是Maven管理的,无法解决依赖项问题,所以工程还需要手动加个asm jar包。
包引用关系如下:
CGLIB demo:
需要代理的目标类 CGLIBBean.java:
package com.company.refectTest;
public class CGLIBBean {
public void sayHi(String value){
System.out.println("Say: " + value);
}
}
Cglib动态代理实现类 CglibExample.java
package com.company.refectTest;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibExample implements MethodInterceptor {
public Object getProxy(Class cls){
//CGLIB enhancer增加类对象
Enhancer enhancer = new Enhancer();
//设置增强类型
enhancer.setSuperclass(cls);
//定义代理逻辑对象为当前对象,要求当前对象实现MethodInterceptor方法
enhancer.setCallback(this);
//生成并返回代理对象
return enhancer.create();
}
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable{
System.err.println("Before.......");
//CGLIB反射调用真实对象方法
Object result = methodProxy.invokeSuper(proxy, args);
System.err.println("After.........");
return result;
}
public void testCGLIBProxy(){
CglibExample cpe = new CglibExample();
CGLIBBean bean = (CGLIBBean)cpe.getProxy(CGLIBBean.class);
bean.sayHi("世界");
}
}
使用:
CglibExample test = new CglibExample();
test.testCGLIBProxy();