我已经尝试了Oracle的Java教程中的两个示例。它们都可以编译,但在运行时,都会出现这个错误:

Exception in thread "main" java.lang.NoClassDefFoundError: graphics/shapes/Square
    at Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: graphics.shapes.Square
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more

我想我可能把Main.java文件放在错误的文件夹里了。

下面是目录层次结构:

graphics
├ Main.java
├ shapes
|   ├ Square.java
|   ├ Triangle.java
├ linepoint
|   ├ Line.java
|   ├ Point.java
├ spaceobjects
|   ├ Cube.java
|   ├ RectPrism.java

这是Main.java:

import graphics.shapes.*;
import graphics.linepoint.*
import graphics.spaceobjects.*;

public class Main {
    public static void main(String args[]) {
        Square s = new Square(2, 3, 15);
        Line l = new Line(1, 5, 2, 3);
        Cube c = new Cube(13, 32, 22);
    }
}

我哪里做错了?

更新

在我把Main类放入图形包之后(我添加了图形包;对于它),将类路径设置为“_test”(包含图形的文件夹),编译它,并使用Java图形运行它。Main(从命令行),它工作正常。

真的很晚更新#2

我没有使用Eclipse(只有notepad++和JDK),上面的更新解决了我的问题。然而,这些答案中似乎有许多是针对Eclipse和IntelliJ IDEA的,但它们具有类似的概念。


当前回答

当运行时类装入器装入的类不能访问已由Java rootloader装入的类时,我得到NoClassFoundError。因为不同的类装入器在不同的安全域中(根据Java), JVM不允许在运行时装入器地址空间中解析已经由rootloader装入的类。

使用'java -javaagent:trace .jar [your 'java' ARGUMENTS]'运行程序

它产生显示已加载类的输出,以及加载该类的加载器环境。追踪类为什么不能解析是非常有用的。

// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5

import java.lang.instrument.*;
import java.security.*;

// manifest.mf
// Premain-Class: ClassLoadTracer

// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class

// java -javaagent:tracer.jar  [...]

public class ClassLoadTracer
{
    public static void premain(String agentArgs, Instrumentation inst)
    {
        final java.io.PrintStream out = System.out;
        inst.addTransformer(new ClassFileTransformer() {
            public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {

                String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
                out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);

                // dump stack trace of the thread loading class
                Thread.dumpStack();

                // we just want the original .class bytes to be loaded!
                // we are not instrumenting it...
                return null;
            }
        });
    }
}

其他回答

Java 11 + Eclipse解决方案:

如果您在Eclipse项目中没有使用module-info.java,并且手动添加JAR文件,而不是使用Maven/Gradle,则此解决方案适合您。

右键单击项目→生成路径→配置生成路径→库选项卡 从模块路径中删除有问题的JAR文件 将JAR文件添加到类路径中

更多信息请参阅 在Eclipse中,modulepath和classpath之间的区别是什么?

在编译代码之后,程序中的每个类都有.class文件。这些二进制文件是Java解释以执行程序的字节码。NoClassDefFoundError表示负责动态加载类的类加载器(在本例中为java.net.URLClassLoader)无法为您试图使用的类找到.class文件。

Your code wouldn't compile if the required classes weren't present (unless classes are loaded with reflection), so usually this exception means that your classpath doesn't include the required classes. Remember that the classloader (specifically java.net.URLClassLoader) will look for classes in package a.b.c in folder a/b/c/ in each entry in your classpath. NoClassDefFoundError can also indicate that you're missing a transitive dependency of a .jar file that you've compiled against and you're trying to use.

例如,如果你有一个类com.example。Foo,编译后你会有一个类文件Foo。class。例如,您的工作目录是…/project/。那个类文件必须放在…/project/com/example,然后将类路径设置为…/project/。

旁注:我建议充分利用Java和JVM语言的惊人工具。像Eclipse和IntelliJ IDEA这样的现代ide和像Maven或Gradle这样的构建管理工具将帮助您不必担心类路径,而将注意力集中在代码上!也就是说,这个链接解释了在命令行上执行时如何设置类路径。

我的观点是:

确保类路径包含完整路径(/home/user/lib/some_lib.jar而不是~/lib/some_lib.jar),否则仍然会面临NoClassDefFoundError错误。

如果你的项目是在一个包,如com。blahcode和你的类被称为Main,编译后的文件可能会以。/out/com/blahcode/Main.class这样的目录结构输出。对于IntelliJ IDEA来说尤其如此。

当试图从shell或cmd运行时,您需要cd到包含com作为子目录的目录。

cd out
java -classpath . com.blahcode.Main

此异常的错误来源之一可能源于Proguard的不一致定义,例如缺少

-libraryJars “path.to.a.missing.jar.library”。

这就解释了为什么在JAR文件存在的情况下,编译和运行工作正常,而清理和构建则失败。记住要在ProGuard设置中定义新添加的JAR库!

请注意,来自ProGuard的错误消息确实不符合标准,因为它们很容易与JAR文件根本不存在时到达的类似Ant消息混淆。只有在最底部才会有ProGuard遇到麻烦的小提示。因此,开始搜索传统的类路径错误等是非常合乎逻辑的,但这将是徒劳的。

显然,NoClassDefFound异常将是运行时的结果,例如,基于缺乏ProGuard一致性构建的可执行JAR文件。有人称之为ProGuard“地狱”。