Java 无法从 class 路径加载 class

Java not able to load a class from class path

我已经在我的 class 路径中添加了一个 jar,例如:

export CLASSPATH="/Users/myname/.m2/repository/org/testng/testng/7.3.0/testng-7.3.0.jar";

当我回应它时,我得到了那个罐子。

不过,我运行我的罐子是这样的:

java -cp target/TestNgExample-1.0-SNAPSHOT.jar:myname org.testng.TestNG testng.xml

但我得到:

Error: Could not find or load main class org.testng.TestNG
Caused by: java.lang.ClassNotFoundException: org.testng.TestNG

如您所见,我将那个 jar 添加到 class 路径,但仍然无法使用它。

有什么帮助吗?

首先:强烈建议不要使用 CLASSPATH 环境变量。

但是,as documented in the manual 在命令行上提供 -cp(或 --class-path)参数会覆盖 CLASSPATH 内容

Specifying classpath overrides any setting of the CLASSPATH environment variable. If the class path option isn't used and classpath isn't set, then the user class path consists of the current directory (.).


要将 TestNG jar 文件包含到您的类路径中,请将其包含在 -cp 参数中:

java -cp target/TestNgExample-1.0-SNAPSHOT.jar:/Users/myname/.m2/repository/org/testng/testng/7.3.0/testng-7.3.0.jar org.testng.TestNG testng.xml