Multiple main methods in a single jar archive

A Java archive file usually holds a manifest file that specifies the main class to start when you invoke java -jar jarfile. It’s something similar to this:

Main-Class: com.yourcom.package.MyClass

When you distribute your jar file, a user can simply execute it (possibly even with a double click) without knowing anything about your package structure or location of the main class.

But what if you want to execute a different main method in another class inside your jar file, maybe for testing purposes? Well, you don’t have to hack the manifest and re-package. Simply do

java -cp jarfile com.yourcom.package.MyClass

and the main method inside MyClass will be executed.

1 thought on “Multiple main methods in a single jar archive

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.