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


当前回答

我从SRC库中删除了两个文件后得到了这个消息,当我把它们带回来时,我一直看到这个错误消息。

我的解决方案是:重新启动Eclipse。从那以后我就再没见过这条消息了:-)

其他回答

当我将另一个模块的Maven依赖添加到我的项目中时,我得到了这个错误,这个问题最终通过添加-Xss2m到我的程序的JVM选项来解决(自JDK5.0以来默认是1m字节)。人们认为程序没有足够的堆栈来加载类。

虽然这可能是由于编译时和运行时之间的类路径不匹配造成的,但这并不一定是真的。

在这种情况下,记住两到三个不同的异常是很重要的:

java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath. java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.

下面的技巧帮助了我很多次:

System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());

其中nodeffoundclass是可能会“丢失”的类,这是由于您的程序使用相同库的旧版本的首选项。当客户端软件被部署到一个占主导地位的容器中,并配备了自己的类加载器和大量最流行的库的古老版本时,这种情况最常发生。

我有这个错误,但无法根据这个线程找出解决方案,但我自己解决了。

对于我的问题,我正在编译以下代码:

package valentines;

import java.math.BigInteger;
import java.util.ArrayList;

public class StudentSolver {
    public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
        //DOING WORK HERE
        
    }
    public static void main(String[] args){
        //TESTING SOLVE FUNCTION
    }
    
}

然后,我在/ProjectName/valentines这样的文件夹结构中编译这段代码 编译它工作得很好,但试图执行:java StudentSolver

我得到了NoClassDefError。

为了解决这个问题,我简单地删除了:包装情人节礼物;

我不是很精通java包等,但这是我如何修复我的错误,非常抱歉,如果这已经由其他人回答,但我无法解释它到我的问题。

有一个有趣的例子,你可能会看到很多NoClassDefFoundErrors:

在类的静态块中抛出一个RuntimeException 拦截它(或者如果它在测试用例中抛出并不重要) 尝试创建该类的实例

static class Example {
    static {
        thisThrowsRuntimeException();
    }
}

static class OuterClazz {

    OuterClazz() {
        try {
            new Example();
        } catch (Throwable ignored) { //simulating catching RuntimeException from static block
            // DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
        }

        new Example(); //this throws NoClassDefFoundError
    }
}

NoClassDefError将伴随来自静态块RuntimeException的ExceptionInInitializerError一起抛出。


当你在UNIT TESTS中看到NoClassDefFoundErrors时,这一点尤其重要。

在某种程度上,您在测试之间“共享”静态块执行,但初始的ExceptionInInitializerError将仅在一个测试用例中。第一个使用有问题的Example类。其他使用Example类的测试用例只会抛出NoClassDefFoundErrors。