如何在Java中解决“找不到或无法加载主类包”问题?


编写Java程序后,需要使用javac命令编译它,这将显示编译时发生的错误(如有)。

解决这些错误并成功编译程序后,将在当前文件夹中生成一个与类名相同的可执行文件,扩展名为.class

然后,需要使用java命令执行它,如下所示:

java class_name

执行时,如果JVM找不到指定名称的.class文件,则会发生运行时错误,显示“找不到或无法加载主类”错误,如下所示:

D:\sample>java Example
Error: Could not find or load main class Example
Caused by: java.lang.ClassNotFoundException: Example

解决方案

为避免此错误,需要指定.class文件的绝对名称(包括包名),该文件位于当前目录中。

以下是可能发生此错误的情况:

类名错误 - 您可能指定了错误的类名。

class Example {
   public static void main(String args[]){
      System.out.println("This is an example class");
   }
}

错误

D:\>javac Example.java
D:\>java Exmple
Error: Could not find or load main class Exmple
Caused by: java.lang.ClassNotFoundException: Exmple

解决方案 - 在这种情况下,类名拼写错误,需要更正。

D:\>javac Example.java
D:\>java Example
This is an example class

大小写错误 - 需要使用与类名相同的大小写来指定类名。Example.java与example.java不同。

class Example {
   public static void main(String args[]){
      System.out.println("This is an example class");
   }
}

错误

D:\>java EXAMPLE
Error: Could not find or load main class EXAMPLE
Caused by: java.lang.NoClassDefFoundError: Example (wrong name: EXAMPLE)

解决方案 - 在这种情况下,类名大小写错误,需要更正。

D:\>javac Example.java
D:\>java Example
This is an example class

包名错误 - 您可能在一个包中创建了.class文件,并尝试在没有包名或使用错误的包名的情况下执行它。

package sample;
class Example {
   public static void main(String args[]){
      System.out.println("This is an example class");
   }
}

错误

D:\>javac -d . Example.java
D:\>java samp.Example
Error: Could not find or load main class samp.Example
Caused by: java.lang.ClassNotFoundException: samp.Example

解决方案 - 在这种情况下,执行时需要指定.class文件所在的正确包名,如下所示:

D:\>javac -d . Example.java
D:\>java sample.Example
This is an example class

包含.class扩展名 - 执行文件时,不需要在程序中包含.class扩展名,只需要指定类文件名即可。

错误

D:\sample>java Example.class
Error: Could not find or load main class Example.class
Caused by: java.lang.ClassNotFoundException: Example.class

解决方案 - 执行程序时不需要 .class扩展名。

D:\sample>java Example
This is an example class

更新于:2019年10月14日

5K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.