从命令行运行具有依赖项的jar [英] Run jar with dependencies from the command line
问题描述
Java可以从命令行运行jar文件,如下所示:
java -jar foobar.jar
但是,如果foobar.jar
依赖于baz.jar
,则一旦调用baz.jar
中的任何类,上面的内容都会引发异常,因为JVM无法知道在哪里寻找这些. /p>
但是,手册页(Linux上为OpenJDK 8)指出:
使用
-jar
选项时,指定的JAR文件是所有用户类的源,而其他类路径设置将被忽略.
如果不能重新打包,是否可以通过命令行运行具有相关性的jar文件?
使用java -jar
时,未在命令行上指定依赖项.
您可以通过2种方式将jar添加到类路径:
-
使用主类调用
java
,并在命令行上添加jar文件,包括您的foobar.jar
:java -cp foobar.jar:baz.jar com.mycompany.MainClass
-
在
foobar.jar
的清单文件中包含依赖项(然后运行java -jar
)Class-Path: baz.jar
Java can run jar files from the command line like this:
java -jar foobar.jar
However, if foobar.jar
depends on baz.jar
, the above will throw an exception as soon as any of the classes in baz.jar
is invoked, as the JVM has no way to know where to look for these.
However, the man page (OpenJDK 8 on Linux) states that:
When you use the
-jar
option, the specified JAR file is the source of all user classes, and other class path settings are ignored.
If repackaging is not an option, is there a way to run a jar file with dependencies from the command line?
When you use java -jar
, dependencies are not specified on the command line.
You have 2 ways to add jars to the class path:
Call
java
with the main class and add jar files, including yourfoobar.jar
, on the command line:java -cp foobar.jar:baz.jar com.mycompany.MainClass
Include dependencies in
foobar.jar
's manifest file (and then runjava -jar
)Class-Path: baz.jar
这篇关于从命令行运行具有依赖项的jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!