Main class in jar

Alan Bateman Alan.Bateman at oracle.com
Mon Mar 5 10:25:08 UTC 2018


On 05/03/2018 09:54, Bernard Amade wrote:
> Hello all
> the doc in https://docs.oracle.com/javase/9/docs/specs/jar/jar.html
> lists for Main-Class entry in jars:
> "attribute defined for stand-alone applications: This attribute is used by stand-alone applications that are bundled into executable jar files which can be invoked by the java runtime directly by running "java -jar x.jar".
> apparently it means that you should not create a modular jar with a manifest template containing a Main-Class entry
> (apparently if you run the app with command "java -module-path dir -m com.thing.app" with the generated com.thing.app.jar the main class will not be found : you get a message saying you've got no Mainclass atrribute)
> but if you generate the jar with a manifest template with no Main-Class entry and instead use the --main-class option then the main class will be found.
> funnily the MANIFEST-MF will then have the same Main-Class entry!
> so what is the difference?
The error message with JDK 9 and JDK 10 has a typo which may be causing 
confusion here. The typo has been fixed for JDK 11 via JDK-8193819 to 
correctly say "ModuleMainClass" attribute. Note that this is a class 
file attribute, not an attribute that you put in the main manifest of a 
JAR file. The `jar` tool will add both when you specify the main class 
with `--main-class` or `-e`.

To summarize:

1. `jar -jar app.jar` is the equivalent of `java -cp app.jar 
<mainclass>` where <mainclass> is value of the Main-Class attribute in 
the main manifest of the JAR file.

2. `java [--module-path <path>] -m <app>` is the way to run a modular 
application on the command line. The app module must have a 
ModuleMainClass class file attribute, something the `jar` tool will do 
for you (Maven plugins and IDEs should do the same but might not be all 
there yet).  The alternative is `-m app/<mainclass>` which you specify 
both the initial/main module and also its main class.

3.  There is no support for executing modular applications with `java -jar`.

-Alan


More information about the jigsaw-dev mailing list