从命令行运行具有依赖项的jar [英] Run jar with dependencies from the command line

查看:66
本文介绍了从命令行运行具有依赖项的jar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java可以从命令行运行jar文件,如下所示:

java -jar foobar.jar

但是,如果foobar.jar依赖于baz.jar,则一旦调用baz.jar中的任何类,上面的内容都会引发异常,因为JVM无法知道在哪里寻找这些. /p>

但是,手册页(Linux上为OpenJDK 8)指出:

使用-jar选项时,指定的JAR文件是所有用户类的源,而其他类路径设置将被忽略.

如果不能重新打包,是否可以通过命令行运行具有相关性的jar文件?

解决方案

使用java -jar时,未在命令行上指定依赖项. 您可以通过2种方式将jar添加到类路径:

  1. 使用主类调用java,并在命令行上添加jar文件,包括您的foobar.jar:

    java -cp foobar.jar:baz.jar com.mycompany.MainClass
    

  2. 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:

  1. Call java with the main class and add jar files, including your foobar.jar, on the command line:

    java -cp foobar.jar:baz.jar com.mycompany.MainClass
    

  2. Include dependencies in foobar.jar's manifest file (and then run java -jar)

    Class-Path: baz.jar
    

这篇关于从命令行运行具有依赖项的jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆