在学习使用CGlib生成动态代理对象,项目的源代码也很简单:
1 package proxy; 2 3 import java.lang.reflect.Method; 4 5 import net.sf.cglib.proxy.Enhancer; 6 import net.sf.cglib.proxy.MethodInterceptor; 7 import net.sf.cglib.proxy.MethodProxy; 8 9 public class CGlibProxy implements MethodInterceptor { 10 11 @SuppressWarnings("unchecked") 12 public <T> T getProxy(Class<T> clazz) { 13 return (T) Enhancer.create(clazz, this); 14 } 15 16 @Override 17 public Object intercept(Object obj, Method method, Object[] args, 18 MethodProxy proxy) throws Throwable { 19 before(); 20 Object result = proxy.invokeSuper(obj, args); 21 after(); 22 return result; 23 } 24 25 private void before() { 26 System.out.println(" before "); 27 28 } 29 30 private void after() { 31 System.out.println(" after "); 32 } 33 34 public static void main(String[] args) { 35 CGlibProxy cGlibProxy = new CGlibProxy(); 36 Hello helloProxy = cGlibProxy.getProxy(HelloImp.class); 37 helloProxy.say("Bob"); 38 39 } 40 }
由于CGlib是第三方的类库,所以要在项目路径中引入CGlib的jar包版本选择了2.2:
不过在运行的时候出现了异常:
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:180) at net.sf.cglib.core.KeyFactory.<clinit>(KeyFactory.java:66) at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69) at proxy.CGlibProxy.getProxy(CGlibProxy.java:13) at proxy.CGlibProxy.main(CGlibProxy.java:36) Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 5 more
报错显示有找不到的类,上网查了以下知道了很多java字节码操作和分析的第三方类库都引用了asm.jar文件,由于工程不是Maven管理的,无法解决以来传递问题,所以要手动引入asm.jar文件。把asm.jar文件添加到项目路径类,运行,然后就正常了。
参考:http://javabeat.net/java-lang-noclassdeffounderror-orgobjectwebasmclassvisitor/