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


当前回答

我在项目中使用Spring Framework和Maven解决了这个错误。

类中存在运行时错误。我将一个属性读取为整数,但是当它从属性文件读取值时,它的值是double。

Spring没有提供运行时在哪一行上失败的完整堆栈跟踪。 它只是说NoClassDefFoundError。但是当我作为一个原生Java应用程序执行它时(将它从MVC中取出),它给出了ExceptionInInitializerError,这是真正的原因,也是我跟踪错误的方式。

@xli的回答让我洞察到我的代码中可能存在的错误。

其他回答

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

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.

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

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

dexOptions {
        preDexLibraries false
        ...

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

每个人都在这里谈论一些Java配置的东西,JVM的问题等,在我的情况下,错误与这些主题完全无关,有一个非常琐碎和容易解决的原因:我在我的控制器(Spring Boot应用程序)的端点有一个错误的注释。

此错误可能是由未检查的Java版本要求引起的。

在我的案例中,当我构建一个备受瞩目的开源项目时,通过使用SDKMAN从Java 9切换到Java 8,我能够解决这个错误。

sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu

然后按照下面的描述进行干净安装。


在使用Maven作为构建工具时,在禁用测试的情况下进行干净的“安装”构建有时是有帮助的,而且通常是令人满意的。

mvn clean install -DskipTests

现在已经构建并安装了所有内容,您可以继续运行测试。

mvn test