简体   繁体   English

从命令行运行带依赖项的jar

[英]Run jar with dependencies from the command line

Java can run jar files from the command line like this: Java可以从命令行运行jar文件,如下所示:

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. 但是,如果foobar.jar依赖于baz.jar ,则baz.jar调用baz.jar任何类,上面将抛出异常,因为JVM无法知道在哪里查找这些类。

However, the man page (OpenJDK 8 on Linux) states that: 但是,手册页(Linux上的OpenJDK 8)声明:

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选项时,指定的JAR文件是所有用户类的源,并忽略其他类路径设置。

If repackaging is not an option, is there a way to run a jar file with dependencies from the command line? 如果重新打包不是一个选项,有没有办法从命令行运行带有依赖项的jar文件?

When you use java -jar , dependencies are not specified on the command line. 使用java -jar ,不在命令行上指定依赖项。 You have 2 ways to add jars to the class path: 您有两种方法可以将jar添加到类路径:

  1. Call java with the main class and add jar files, including your foobar.jar , on the command line: 使用主类调用java并在命令行上添加jar文件,包括foobar.jar

     java -cp foobar.jar:baz.jar com.mycompany.MainClass 
  2. Include dependencies in foobar.jar 's manifest file (and then run java -jar ) foobar.jar的清单文件中包含依赖foobar.jar (然后运行java -jar

     Class-Path: baz.jar 

I believe you have only 'one' main class in foobar.jar. 我相信你在foobar.jar中只有一个主要课程。 If it is more then 1, then you need to specify which one to execute. 如果它大于1,那么您需要指定执行哪一个。
You can simply set the classpath, before executing the jar 在执行jar之前,您可以简单地设置类路径

export CLASSPATH=$CLASSPATH:/JAR_LOCATION/bar.jar


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

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