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


当前回答

当我试图在Tomcat/JBOSS服务器上部署应用程序时,我得到了NoClassDefFoundError。我尝试了不同的依赖关系来解决这个问题,但总是得到相同的错误。标记所有javax。*依赖提供在pom.xml,和战争字面上没有依赖。但这个问题还是不断出现。

最终意识到src/main/webapps/WEB-INF/classes有类文件夹被复制到我的战争,所以不是编译类,这个类被复制,因此没有依赖改变解决问题。

因此要小心,如果任何以前编译的数据被复制,删除类文件夹和新的编译后,它工作!..

其他回答

当静态初始化器试图加载一个在运行时不可用的资源包时,也会发生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);
}

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

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

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.

在我的情况下,由于JDK版本不匹配,我得到了这个错误。当我试图从Intelij运行应用程序时,它不工作,但从命令行运行它就工作了。这是因为Intelij试图用Java 11 JDK运行它,但在命令行上,它是用Java 8 JDK运行的。在文件>项目结构>项目设置>项目SDK下切换设置后,它为我工作了。

我通过禁用所有模块的preDexLibraries来解决我的问题:

dexOptions {
        preDexLibraries false
        ...

有一个有趣的例子,你可能会看到很多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。