短格式:如果你的 main 在一个 jar 中,你可能需要一个额外的 '-jar pathTo/yourJar/YourJarsName.jar '明确声明让它工作(即使 'YourJarsName.jar' 在类路径上)
(或者,表达回答 5 年前提出的原始问题:您不需要明确地重新声明每个 jar,但似乎,即使使用 java6,您也需要重新声明自己的 jar ...)
长格式:
(我已经明确表达了这一点,我希望即使是 java 的闯入者也能利用这一点)
像这里的许多人一样,我使用 eclipse 来导出 jars:(文件->导出-->'可运行的 JAR 文件')。 '库处理' eclipse (Juno) 提供三个选项:
opt1: "Extract required libraries into generated JAR"
opt2: "Package required libraries into generated JAR"
opt3: "Copy required libraries into a sub-folder next to the generated JAR"
通常我会使用 opt2(并且 opt1 肯定会破坏),但是我正在使用的其中一个 jar 中的本机代码发现在您选择该选项时 eclipse 会利用方便的“jarinjar”技巧破坏。即使在意识到我需要 opt3,然后找到这个 StackOverflow 条目之后,我仍然花了一些时间来弄清楚如何在 eclipse 之外启动我的 main,所以这对我有用,因为它对其他人有用......
如果您将 jar 命名为:“fooBarTheJarFile.jar”
并且全部设置为导出到目录:“/theFully/qualifiedPath/toYourChosenDir”。
(意味着“导出目的地”字段将显示为:“/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar”)
点击完成后,您会发现 eclipse 然后将所有库放入该导出目录中名为“fooBarTheJarFile_lib”的文件夹中,为您提供如下内容:
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar01.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar02.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar03.jar
/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar04.jar
然后您可以从系统上的任何位置启动:
java -classpath "/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/*" -jar /theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar package.path_to.the_class_with.your_main.TheClassWithYourMain
(对于 Java 新手:'package.path_to.the_class_with.your_main' 是声明的包路径,您可以在包含 'main(String[] args) 的 'TheClassWithYourMain.java' 文件的顶部找到它{...}' 你希望从外部 java 运行)
需要注意的缺陷是:在声明的类路径中的 jar 列表中包含“fooBarTheJarFile.jar”是不够的。您需要显式声明“-jar”,并重新声明该 jar 的位置。
例如这打破了:
java -classpath "/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar;/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/*" somepackages.inside.yourJar.leadingToTheMain.TheClassWithYourMain
用相对路径重述:
cd /theFully/qualifiedPath/toYourChosenDir/;
BREAKS: java -cp "fooBarTheJarFile_lib/*" package.path_to.the_class_with.your_main.TheClassWithYourMain
BREAKS: java -cp ".;fooBarTheJarFile_lib/*" package.path_to.the_class_with.your_main.TheClassWithYourMain
BREAKS: java -cp ".;fooBarTheJarFile_lib/*" -jar package.path_to.the_class_with.your_main.TheClassWithYourMain
WORKS: java -cp ".;fooBarTheJarFile_lib/*" -jar fooBarTheJarFile.jar package.path_to.the_class_with.your_main.TheClassWithYourMain
(使用 java 版本“1.6.0_27”;通过 ubuntu 12.04 上的 OpenJDK 64 位服务器 VM)