Creating Jar archive gives “Could not find or load main class”

时光毁灭记忆、已成空白 提交于 2019-12-24 17:28:33

问题


$ cat Manifest.txt 
Main-Class: org.fenix.llanfair.Llanfair

$ cat org/fenix/llanfair/Llanfair.java | grep main
public static void main(String[] args) {
$ jar cfm Llanfair.jar Manifest.txt org
$ java -jar Llanfair.jar 
Error: Could not find or load main class org.fenix.llanfair.Llanfair
$ jar -xf Llanfair.jar
$ cat Llanfair/META-INF/MANIFEST.MF 
Manifest-Version: 1.0
Created-By: 1.8.0_25 (Oracle Corporation)
Main-Class: org.fenix.llanfair.Llanfair

$ ls Llanfair/org/fenix/llanfair/ | grep Llanfair
Llanfair$1.class
Llanfair$2.class
Llanfair$MenuItem.class
Llanfair$RecentMenuItem.class
Llanfair.class
$ java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

I expect java -jar Llanfair.jar to start my application, so I'm not sure what I'm doing wrong here. I do have a couple of files in lib/ which are on my classpath when I run the java code normally, do I need to include those?

My OS is Mac OS 10.11.1, if it matters.


回答1:


Seems the file structure in Llanfair.jar is wrong.

Based on your comment jar -xf Llanfair.jar creates a structure like

Llanfair/META-INF/MANIFEST.MF 
Llanfair/org/fenix/llanfair/Llanfair.class

But the structure inside the jar file must be

META-INF/MANIFEST.MF 
org/fenix/llanfair/Llanfair.class



回答2:


I was missing the Class-Path: value in the manifest, why it would appear in this way is beyond me.

$ cat Manifest.txt
Class-Path: lib/ui.jar lib/jnativehook-2.0.2.jar
Main-Class: org.fenix.llanfair.Llanfair

$ jar cfm Llanfair.jar Manifest.txt org lib
$ java -jar Llanfair.jar 
<normal application output>
^C$ jar -xf Llanfair.jar
$ ls Llanfair
ls: Llanfair: No such file or directory
<manually extracted Llanfair.jar using Archive Utility>
$ cat Llanfair/META-INF/MANIFEST.MF 
Manifest-Version: 1.0
Class-Path: lib/ui.jar lib/jnativehook-2.0.2.jar
Created-By: 1.8.0_25 (Oracle Corporation)
Main-Class: org.fenix.llanfair.Llanfair

$

Edit: It's a little more complex. I was trying to include the jar dependencies in Llanfair.jar. This is not allowed because /reasons/. The above was working because I was running the jar in the same directory -- so lib/ui.jar was present because I was using it to build.



来源:https://stackoverflow.com/questions/33689262/creating-jar-archive-gives-could-not-find-or-load-main-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!