简体   繁体   English

为什么我的程序找不到我的Java类?

[英]Why does my program not find my java classes?

I have a project that I have compiled to a jar with Maven which I named H.jar. 我有一个项目,已使用Maven编译为jar,我将其命名为H.jar。 The maven command I use is (in eclipse): 我使用的Maven命令是(在Eclipse中):

maven install

The jar file has a class called Person in it. jar文件中包含一个名为Person的类。 I have added the jar file to the classpath on a Windows machine. 我已将jar文件添加到Windows计算机上的类路径中。

echo %classpath%
Results -> C:\location_to_jar\H.jar

But when I try to compile the program I get error: 但是,当我尝试编译程序时,出现错误:

error. Cannot find symbol.

I am running the command: 我正在运行命令:

javac Main.java

The class looks like this: 该类如下所示:

public class Main {
     public static void main(String[] args) {
     Person p = new Person("John", "Doe");
     p.toString();
     }
}

Should the program not just find the class if I have added it to the classpath? 如果我将其添加到类路径中,程序是否应该不仅找到该类?

It sounds like your program is fully contained within a single jar, with no external dependencies, so I would recommend that you avoid using the %CLASSPATH% environment variable. 听起来您的程序完全包含在一个jar中,没有任何外部依赖关系,所以我建议您避免使用%CLASSPATH%环境变量。 Instead, point Java at the jar directly. 而是直接将Java指向jar。

Assuming that your Maven build has generated an executable jar with your Main class defined as its entry point then you can just execute: 假设您的Maven构建已经生成了一个将Main类定义为其入口点的可执行jar,那么您可以执行以下命令:

java -jar C:\location_to_jar\H.jar

If the executable class has not been defined in your build, then you can define the classpath on the command line: 如果尚未在构建中定义可执行类,则可以在命令行上定义类路径:

java -cp C:\location_to_jar\H.jar com.mypackage.Main

You will need to replace the package in the command above with the appropriate package name as defined in your application. 您将需要使用应用程序中定义的适当软件包名称替换上面命令中的软件包。

If you want Maven to make your jar executable, then you can use the Maven Assembly Plugin to help. 如果希望Maven使jar可执行文件,则可以使用Maven组件插件来提供帮助。 An answer which explains that can be found here: How can I create an executable JAR with dependencies using Maven? 可以在这里找到答案的答案: 如何使用Maven创建具有依赖项的可执行JAR?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM