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

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

问题描述

Java 可以像这样从命令行运行 jar 文件:

Java can run jar files from the command line like this:

java -jar foobar.jar

然而,如果foobar.jar依赖于baz.jar,那么只要baz.jar<中的任何一个类,上面的代码都会抛出异常/code> 被调用,因为 JVM 无法知道在哪里寻找这些.

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.

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

However, the man page (OpenJDK 8 on Linux) states that:

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

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

如果重新打包不是一种选择,有没有办法从命令行运行带有依赖项的 jar 文件?

If repackaging is not an option, is there a way to run a jar file with dependencies from the command line?

推荐答案

当您使用 java -jar 时,不会在命令行中指定依赖项.您有两种方法可以将 jar 添加到类路径中:

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. 使用主类调用 java 并在命令行上添加 jar 文件,包括您的 foobar.jar:

  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

  • foobar.jar 的清单文件中包含依赖项(然后运行 ​​java -jar)

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

    Class-Path: baz.jar
    

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

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