java - NoClassDefFoundError 和 ClassNotFoundException 的原因和区别是什么?

标签 java classpath noclassdeffounderror classnotfoundexception

NoClassDefFoundErrorClassNotFoundException 有什么区别?

什么原因导致它们被抛出?如何解决?

在修改现有代码以包含新的 jar 文件时,我经常遇到这些可抛出的问题。 我已经在客户端和服务器端找到了通过 webstart 分发的 java 应用程序。

我遇到的可能原因:

  1. 客户端代码的 build.xml 中未包含的软件包
  2. 我们正在使用的新 jar 缺少运行时类路径
  3. 版本与以前的 jar 冲突

当我今天遇到这些问题时,我会采取试错法来让事情正常运转。我需要更多的清晰度和理解。

最佳答案

与Java API规范的区别如下。

对于ClassNotFoundException :

Thrown when an application tries to load in a class through its string name using:

  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader.
  • The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.

对于NoClassDefFoundError :

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

因此,当源代码成功编译时,似乎会发生 NoClassDefFoundError ,但在运行时,找不到所需的 class 文件。这可能是在 JAR 文件的分发或生产过程中发生的情况,其中并未包含所有必需的 class 文件。

至于ClassNotFoundException,看起来它可能源于尝试在运行时对类进行反射调用,但程序尝试调用的类不存在。

两者之间的区别在于,一个是Error,另一个是ExceptionNoClassDefFoundError 是一个 Error,它是由于 Java 虚拟机在查找它期望找到的类时出现问题而引起的。预计在编译时运行的程序无法运行,因为未找到 class 文件,或者与编译时生成或遇到的文件不同。这是一个非常严重的错误,因为 JVM 无法启动该程序。

另一方面,ClassNotFoundException 是一个 Exception,因此它在某种程度上是预期的,并且是可恢复的。使用反射可能容易出错(因为有人期望事情可能不会按预期进行。没有编译时检查来查看所有必需的类是否存在,因此查找所需类的任何问题都会在运行时出现.

关于java - NoClassDefFoundError 和 ClassNotFoundException 的原因和区别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56615702/

相关文章:

java 类路径意外地找到了一个库

java - 在您的类路径中找不到编译器! (您可能需要添加 'tools.jar' )Axis 1.4 + Tomcat 9.0

Android studio 和 NoClassDefFoundError

java - 多级包 - Java

java - NullPointer 异常 2D 数组类

java - ResultSet 抛出 NullPointers,但 next() 返回 true

java - Intellij 类路径错误 由 : java. io.FileNotFoundException 引起

java - Thread.currentThread().setContextClassLoader 似乎无法正常工作

java - "Could not find the main class: MineAvtaler. Program will exit."- 仅当在 Eclipse 外部运行时

java - 从java在mysql中创建一个数据库