tags:

views:

192

answers:

5

Please correct me if I am wrong.

When running java [-options] -jar jarfile with no explicit class name, if a single class exists within the jar that contains a public static void main(String[] args) method, that method will be invoked automatically. Right?

What happens if I have several classes that contain an eligible main method?

+3  A: 

The class to run is taken from the Manifest metadata.

Main-Class :

The value of this attribute defines the relative path of the main application class which the launcher will load at startup time. The value must not have the .class extension appended to the class name.

Thomas Jung
Great answer, sorry I can't choose more than one as the accepted answer.
Yaneeve
+5  A: 

It uses the Main-Class defined in the MANIFEST file to determine which class contains the main method that should be run.

see http://java.sun.com/docs/books/tutorial/deployment/jar/appman.html

digitaljoel
Note: If you're using Ant to do your building, it's possible to have Ant build your MANIFEST file for you. I've found it to be very handy to not have to manually keep that file up to date.
John Munsch
+2  A: 

The JAR must contain a manifest file with a "Main-Class" entry.

Edit: I recall at one point the docs were incorrect. If "Main-Class" doesn't work for you, try "Main-class" (lowercase "class").

kdgregory
+2  A: 

Which class' main is run is determined by the MANIFEST file inside the .jar. Specifically the Main-Class attribute.

rsp
+2  A: 

If you attempt to use java -jar on a jar without the above said manifest, you'll get the following output:

Failed to load Main-Class manifest attribute from <jarname>.jar
Jason Nichols