gpt4 book ai didi

java - 解决 Java 中的 NoClassDefFoundError

转载 作者:搜寻专家 更新时间:2023-10-31 08:21:09 24 4
gpt4 key购买 nike

我有一个名为 Main.java 的 Java 程序,它位于以下目录中:

/home/user/program/Main.java

当我尝试从“程序”目录运行 Main.java 时,一切正常,我使用了这一行:

/home/user/program$ java Main

但是当我尝试从主目录运行 Main.java 时:

/home$ java /home/user/program/Main

我明白了:

Exception in thread "main" java.lang.NoClassDefFoundError: /home/user/program/Main
Caused by: java.lang.ClassNotFoundException: .home.user.program.Main

这个错误的原因是什么?

最佳答案

这是由于您的类路径,默认为当前目录。当您从 /home/user/program 运行 java Main 时,它会在当前目录中找到该类(因为包似乎未设置,这意味着它是默认值)。因此,它在 /home/user/program/Main.class 中找到该类。

/home 运行 java/home/user/program/Main 尝试在类路径(当前目录)中找到类,它将在 中查找/home/home/user/program 希望找到包含 Main 类定义的文件 Main.class.home.user .程序.

Extra detail: I think the java launcher is trying to be nice by converting /-notation for a classname to the .-notation; and when you run java /home/user/program/Main it is actually running java
.home.user.program.Main
for you. This is because you shouldn't be specifying a file, but a fully specified classname (ie including package specifier). And when a class has a package java expects to find that class within a directory structure that matches the package name, inside a directory (or jar) in the classpath; hence, it will try to look in /home/home/user/program for the class file

您可以通过使用 -cp-classpath 指定您的类路径来修复它:

java -cp /home/user/program Main

关于java - 解决 Java 中的 NoClassDefFoundError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5376311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com