java 运行jar classpath,从命令行运行JAR文件并指定classpath

当尝试从命令行运行包含依赖库的JAR文件时,遇到找不到主类或NoClassDefFoundError的问题。解决方案包括:1) 在JAR的manifest中包含所有lib目录下的jar文件;2) 使用`java -cp`命令指定类路径,包括JAR文件本身和lib目录。例如:`java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I've compiled a JAR file and specified the Main-Class in the manifest (I used the Eclipse Export function). My dependencies are all in a directory labeled lib. I can't seem to get a straight answer on how to execute my JAR file while specifying it should use the lib/* as the classpath.

I've tried:

]$ java -jar -cp .:lib/* MyJar.jar

]$ java -cp .:lib/* -jar MyJar.jar

]$ java -cp .:lib/* com.somepackage.subpackage.Main

etc...

Each gives an error saying:

Error: Could not find or load main class ....

or gives the NoClassDefFoundError indicating the libraries are not being found.

I even tried remaking the JAR file and included the lib directory and contents, but still no dice...

How can I execute a JAR file from the command line and specify the classpath to use?

解决方案

When you specify -jar then the -cp parameter will be ignored.

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

include all jar files from the lib directory into the manifest (you can use relative paths there)

Specify everything (including your jar) on the commandline using -cp:

java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值