[原创] java.lang.NoClassDefFoundError 的解决方法一例

看清楚了,这个错误可不是java.lang.ClassNotFoundExceptionClassNotFoundException通常是由jar包缺失造成的,编译通不过,自然就知道少了什么,而java.lang.NoClassDefFoundError是有可能编译通过的。
我遇到的这个情况,也是编译jar包能通过,但是在运行unit test的时候总是fail。
运行unit test输出的错误信息大致如下:

java.lang.NoClassDefFoundError: javassist/NotFoundException
    at org.apache.curator.test.TestingServer.<clinit>(TestingServer.java:32)
    ......

其实后面还有很多信息,不过它们都不重要。
首先在这里我犯了个严重的错误,那就是没有仔细看“java.lang.NoClassDefFoundError: javassist/NotFoundException”这句话。由于ant编译jar包可以成功,所以我就想当然地认为已经不缺少任何jar包,结果在运行unit test的时候老是出这个错,所以我就没往缺少jar包这方面想,总是在苦苦探索它到底是其他什么原因造成的。
但事实上这句错误消息已经提示了“javassist”,这就是运行unit test时缺少的jar包。尽管没有给出版本,但是我在Maven Central网站上搜索下载了一个最新的版本,经测试是可用的。

然后我再次运行unit test,发现又提示另一个method找不到的问题,这回一看,原来是我使用的Guava版本太低导致的,于是更新到最新版,搞定!

话又说回来,NoClassDefFoundError 到底和 ClassNotFoundException 有什么区别呢?NoClassDefFoundError到底有哪些解决办法,应该怎么查呢?在解决这个问题的过程中,我觉得这篇文章给了我特别大的帮助。在此,截取部分内容如下:

NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time. For example if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw NoClassDefFoundError. It’s important to understand that this is different than ClassNotFoundException which comes while trying to load a class at run-time only and name was provided during runtime not on compile time. Many Java developer mingle this two Error and gets confused.
 
In short NoClassDefFoundError will come if a class was present during compile time but not available in java classpath during runtime. 

Many a times we confused ourselves with java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError, though both of them related to Java Classpath they are completely different to each other. ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws java.lang.ClassNotFoundException. While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason. NoClassDefFoundError is easier to solve than ClassNotFoundException in my opinion because here we know that Class was present during build time but it totally depends upon environment, if you are working in J2EE environment than you can get NoClassDefFoundError even if class is present because it may not be visible to corresponding ClassLoader. 

文章来源:http://www.codelast.com/
此外,stackoverflow的一些文章(例如这篇)也建议在发生此错误时从class的static部分开始查,而触发我的这个错误的,正好就是在我的class的static部分。

文章来源:https://www.codelast.com/
➤➤ 版权声明 ➤➤ 
转载需注明出处:codelast.com 
感谢关注我的微信公众号(微信扫一扫):

wechat qrcode of codelast

发表评论