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


当前回答

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

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

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

其他回答

这是迄今为止我找到的最好的解决办法。

假设我们有一个名为org的包。Mypackage包含的类:

HelloWorld(主类) SupportClass UtilClass

定义这个包的文件物理存储在目录D:\myprogram (Windows)或/home/user/myprogram (Linux)下。

文件结构如下所示:

当调用Java时,我们指定要运行的应用程序的名称:org.mypackage.HelloWorld。但是,我们还必须告诉Java在哪里查找定义包的文件和目录。所以要启动程序,我们必须使用下面的命令:

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

Java无法在运行时找到类A。 Class A在maven项目ArtClient中,来自不同的工作空间。 因此,我将ArtClient导入到Eclipse项目中。 我的两个项目使用ArtClient作为依赖项。 我将这些库引用更改为项目引用(构建路径->配置构建路径)。

问题就这样解决了。

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