使用CGlib出現java.lang.NoClassDefFoundError: org/objectweb/asm/Type異常

在學習使用CGlib生成動態代理對象,項目的源代碼也很簡單:java

 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:web

不過在運行的時候出現了異常:ide

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/this

相關文章
相關標籤/搜索