有时,在用"java -jar"来执行一个jar时,总是报错说找不到main方法。这个问题一般是因为MANIFEST.MF中缺少"Main-Class"的属性来指定包含main方法的class文件名。
正确的方法是解压jar包,修改里面的MANIFEST.MF,加入Main-Class属性,然后使用jar命令来重新制作jar包。
$ tree
├── com
│ └── j2se
│ ├── BinarySearch.class
│ └── BinarySearch.java
├── META-INF
│ └── MANIFEST.MF
修改MANIFEST.MF文件如下:
0> cat META-INF/MANIFEST.MF
Manifest-Version: 1.0
Built-By: user
Build-Jdk: 1.7.0_45
Created-By: Apache Maven 3.1.1
Archiver-Version: Plexus Archiver
Main-Class: com.j2se.BinarySearch
制作jar
jar cvfm binary_search-1.0.3.jar META-INF/MANIFEST.MF com/j2se/BinarySearch.class
# if "m" option not given, the MANIFEST.MF will be overrded during the process of creating jar.
这里的选项m必须给定,否着在制作jar的过程中,会自动生成一份新的MANIFEST.MF文件,且不含有Main-Class属性。
如下是jar的用法:
0> jar
Usage: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
Options:
-c create new archive
-t list table of contents for archive
-x extract named (or all) files from archive
-u update existing archive
-v generate verbose output on standard output
-f specify archive file name
-m include manifest information from specified manifest file
-e specify application entry point for stand-alone application
bundled into an executable jar file
-0 store only; use no ZIP compression
-M do not create a manifest file for the entries
-i generate index information for the specified jar files
-C change to the specified directory and include the following file
If any file is a directory then it is processed recursively.
The manifest file name, the archive file name and the entry point name are
specified in the same order as the 'm', 'f' and 'e' flags.
Example 1: to archive two class files into an archive called classes.jar:
jar cvf classes.jar Foo.class Bar.class
Example 2: use an existing manifest file 'mymanifest' and archive all the
files in the foo/ directory into 'classes.jar':
jar cvfm classes.jar mymanifest -C foo/ .