当我运行Java应用程序时,我得到了一个NoClassDefFoundError。造成这种情况的典型原因是什么?
当前回答
当我将另一个模块的Maven依赖添加到我的项目中时,我得到了这个错误,这个问题最终通过添加-Xss2m到我的程序的JVM选项来解决(自JDK5.0以来默认是1m字节)。人们认为程序没有足够的堆栈来加载类。
其他回答
下面是演示java.lang.NoClassDefFoundError的代码。具体的解释请看Jared的回答。
NoClassDefFoundErrorDemo.java
public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
try {
// The following line would throw ExceptionInInitializerError
SimpleCalculator calculator1 = new SimpleCalculator();
} catch (Throwable t) {
System.out.println(t);
}
// The following line would cause NoClassDefFoundError
SimpleCalculator calculator2 = new SimpleCalculator();
}
}
SimpleCalculator.java
public class SimpleCalculator {
static int undefined = 1 / 0;
}
我发现,当使用运行时发现的不兼容的类版本编译代码时,有时会得到NoClassDefFound错误。我记得的具体实例是apache axis库。在我的运行时类路径上实际上有2个版本,它正在挑选过时和不兼容的版本,而不是正确的版本,导致NoClassDefFound错误。这是在一个命令行应用程序中,我正在使用类似的命令。
set classpath=%classpath%;axis.jar
我能够让它拿起正确的版本使用:
set classpath=axis.jar;%classpath%;
当我没有在项目的Java Build Path中的“Order and export”选项卡上导出一个类时,我得到了NoClassDefFound错误。确保在添加到项目构建路径的任何依赖项的“Order and Export”选项卡中添加一个复选标记。请参见Eclipse警告:XXXXXXXXXXX.jar将不会被导出或发布。可能会导致运行时ClassNotFoundExceptions。
同一项目的两个不同的签出副本
In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.
关闭项目的主干副本并再次运行测试用例可以解决这个问题。
当静态初始化器试图加载一个在运行时不可用的资源包时,也会发生NoClassDefFoundError,例如受影响的类试图从META-INF目录加载一个属性文件,但不存在。如果你没有捕获NoClassDefFoundError,有时你将无法看到完整的堆栈跟踪;为了克服这个问题,你可以临时为Throwable使用一个catch子句:
try {
// Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}
推荐文章
- getResourceAsStream返回null
- 如何使用Java中的Scanner类从控制台读取输入?
- 如何添加JTable在JPanel与空布局?
- Statement和PreparedStatement的区别
- 为什么不能在Java中扩展注释?
- 在Java中使用UUID的最重要位的碰撞可能性
- 转换列表的最佳方法:map还是foreach?
- 如何分割逗号分隔的字符串?
- Java字符串—查看字符串是否只包含数字而不包含字母
- Mockito.any()传递带有泛型的接口
- 在IntelliJ 10.5中运行测试时,出现“NoSuchMethodError: org.hamcrest. matcher . descripbemismatch”
- 使用String.split()和多个分隔符
- Java数组有最大大小吗?
- 在Android中将字符串转换为Uri
- 从JSON生成Java类?