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


当前回答

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

其他回答

这是由于您的代码所依赖的类文件在编译时存在,但在运行时没有找到。寻找构建时和运行时类路径的差异。

下面是演示java.lang.NoClassDefFoundError的代码。具体的解释请看Jared的回答。

NoClassDefFoundErrorDemo.java

public class NoClassDefFoundErrorDemo {
    public static void main(String[] args) {
        try {
            // The following line would throw ExceptionInInitializerError
            SimpleCalculator calculator1 = new SimpleCalculator();
        } catch (Throwable t) {
            System.out.println(t);
        }
        // The following line would cause NoClassDefFoundError
        SimpleCalculator calculator2 = new SimpleCalculator();
    }

}

SimpleCalculator.java

public class SimpleCalculator {
    static int undefined = 1 / 0;
}

Java ClassNotFoundException vs NoClassDefFoundError

黑ClassLoader铝

静态与动态类加载

静态(隐式)类加载——引用、实例化或继承的结果。

MyClass myClass = new MyClass();

动态(显式)类加载是class . forname (), loadClass(), findSystemClass()的结果

MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();

每个类都有一个ClassLoader,它使用loadClass(字符串名);这就是为什么

explicit class loader uses implicit class loader

NoClassDefFoundError是显式类装入器的一部分。Error是为了保证在编译期间出现这个类,但现在(在运行时)它不存在。

ClassNotFoundException是隐式类装入器的一部分。Exception对于可以额外使用的场景(例如反射)具有弹性。

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

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

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