Java错误: 无法找到或加载主类 (ClassNotFoundException)

huangapple go评论96阅读模式
英文:

Java Error: Could not find or load main class (ClassNotFoundException)

问题

我有一个Java文件hello.java

public class hello {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}

我输入javac hello.java命令进行编译,并成功在相同路径下生成了一个.class文件(反编译版本)。

// 源代码不可用,并由Fernflower反编译器生成。
public class hello {
   public static void main(String[] var0) {
      System.out.println("Hello World");
   }
}

然而,当我尝试用java hello命令运行hello类的主函数时,它总是抛出ClassNotFoundException。

PS D:\Study\JAVA> java hello
错误: 找不到或无法加载主类hello

当我尝试使用VS Code的内部调试功能时,主函数正常工作,因此我可以确认内部没有错误。

我也可以确认我在命令中使用的类名完全正确。我不明白为什么会一直显示这个ClassNotFoundException。

我知道这只是一个非常基本的问题(也许很愚蠢)。非常感谢任何可能的答案。

我正在使用Java 1.8.0_311。

我用javac hello.java编译了Java文件,它正常工作。
然后我可以看到一个Java类文件 - hello.class已经生成。
我尝试了很多次运行java hello,但总是得到ClassNotFoundException。
我尝试重启IDE或删除并重新编写整个文件,但都没有用。

英文:

I have a java file hello.java

public class hello{
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}

I entered javac hello.java command to compile it and successfully generated a .class file in the same path hello.class (decomplied version)

 // Source code is unavailable, and was generated by the Fernflower decompiler.
public class hello {
   public static void main(String[] var0) {
      System.out.println("Hello World");
   }
}

However when I try to run the main function for hello class with the command java hello, it always turn out to throw a ClassNotFoundException

PS D:\Study\JAVA> java hello
Error: Could not find or load main class hello

When I tried internal debug feature of VS Code, the main function worked normally so I can confirm that the function inside has no error.

I can also confirm the class name I applied in my command completely correct. I dont understand why this ClassNotFoundException always show up.

I know it's just a very basic question (maybe stupid). Many thanks for any possible answer.

I'm using java 1.8.0_311

I compiled the java file with javac hello.java and it works normally.
Then I can see a java class file - hello.class has been generated.
I tried many times to run java hello but always get ClassNotFoundException.
I have tried restarting the IDE or delete and rewriting the whole file but none of them works.

答案1

得分: 0

这对我来说是有效的(在Linux上)。然而,我没有在Windows上安装Java来进行测试。

您可以尝试 java -cp . hello,这将明确设置类路径为当前目录,这应该允许 java 找到该类。

英文:

Doing exactly that works for me (on Linux). However, I don't have java installed on Windows to test.

You can try java -cp . hello which will explicitly set the classpath to the current directory, which should allow java to find the class.

huangapple
  • 本文由 发表于 2023年6月22日 08:52:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528015.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定