使用包时获取java.lang.ClassNotFoundException [英] Getting java.lang.ClassNotFoundException when using package
问题描述
我有一个带有以下代码的Java文件ComPac.java
:
I have a java file ComPac.java
with the below code:
package com;
public class ComPac{
public static void main(String[] args) {
System.out.println("Hello World");
}
}
文件位于路径:/home/ec2-user/java_c
要编译此文件,我运行了javac Compac.java
,并生成了类文件.
To compile this file, I ran javac Compac.java
, and the class file was generated.
现在该运行类文件了.
所以我做了java ComPac
(下面的屏幕截图)
So I did java ComPac
(screenshot below)
可以理解,我收到了错误Error: Could not find or load main class ComPac. Caused by: java.lang.NoClassDefFoundError: com/ComPac (wrong name: ComPac).
我假设这是因为java文件中声明了软件包com
.
Understandably, I got the error Error: Could not find or load main class ComPac. Caused by: java.lang.NoClassDefFoundError: com/ComPac (wrong name: ComPac).
This I am assuming is because the java file has the package com
declared in it.
因此,我尝试了java com.ComPac
并期望它可以正常工作(下面的屏幕截图).
So instead I tried, java com.ComPac
and expected it to work(screenshot below).
但是我得到了错误:Error: Could not find or load main class com.ComPac. Caused by: java.lang.ClassNotFoundException: com.ComPac
.
那么我该如何运行呢?在使用Java包时运行的逻辑到底是什么?
So how do I run this? and what exactly is the logic for running when it comes to packages in java?
使用过的Java-openjdk version "11.0.8" 2020-07-14 LTS(AWS Corretto)
使用的操作系统-Amazon Linux 2
推荐答案
将该类放在一个名为"com"的文件夹中.
put the class in a folder called "com"
然后在bash外壳中:
in a bash shell it's then:
$ java com/ComPac
(来自包含"com"的文件夹,而不是"com"内部)
(from the folder containing "com", not inside of "com")
这篇关于使用包时获取java.lang.ClassNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!