当我运行Java应用程序时,我得到了一个NoClassDefFoundError。造成这种情况的典型原因是什么?


当前回答

如果您有生成代码(EMF等),可能会有太多的静态初始化器,这会占用所有的堆栈空间。

参见堆栈溢出问题如何增加Java堆栈大小?。

其他回答

同一项目的两个不同的签出副本

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.

关闭项目的主干副本并再次运行测试用例可以解决这个问题。

这也可能是因为您从具有特定包名的IDE复制了代码文件,并且希望尝试使用终端运行它。您必须首先从代码中删除包名。 这种事发生在我身上。

下面是演示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;
}

这是由于您的代码所依赖的类文件在编译时存在,但在运行时没有找到。寻找构建时和运行时类路径的差异。

如果有人因为java.lang.NoClassDefFoundError: org/apache/log4j/Logger错误来到这里,在我的例子中,它是因为我使用了log4j 2(但我没有添加它附带的所有文件),而一些依赖库使用了log4j 1。解决方案是添加Log4j 1。X桥:log4j-1.2-api-<version>.jar,随log4j 2而来。更多信息在log4j 2迁移中。