cglib出现java.lang.NoClassDefFoundError求指教
被代理的类:public class User {
private int age;
private String name;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public int age() {
return age;
}
public String name() {
return name;
}
public void run() {
System.out.println("我的run方法执行了");
}
public void test() {
System.out.println("我的test方法执行了");
}
public String toString() {
return name + "=" + age;
}
}
生成被代理类的子类作为代理类:
package CGLIB;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class MyMethodInterceptor implements MethodInterceptor{
public Object target;
public Object getInstance(Object target) {
this.target = target;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
Object b = arg3.invokeSuper(arg1,arg2);
return b;
}
}
使用:
package CGLIB;
public class Main {
public static void main(String[] args) {
MyMethodInterceptor mmi = new MyMethodInterceptor();
User user = (User)mmi.getInstance(new User());
user.run();
}
}
错误:
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:66)
at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69)
at CGLIB.MyMethodInterceptor.getInstance(MyMethodInterceptor.java:13)
at CGLIB.Main.main(Main.java:6)
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
at (Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more