1. Overview
Every executable Java class has to contain a main method. Simply put, this method is a starting point of an application.
To run our main method from a self-executing JAR file, we have to create a proper manifest file and pack it along with our code. This manifest file has to have a main manifest attribute that defines the path to the class containing our main method.
In this tutorial, we’ll show how to pack a simple Java class as a self-executing JAR and demonstrate the importance of a main manifest attribute for a successful execution.
2. Executing a JAR Without the Main Manifest Attribute
To get more practical, we’ll show an example of unsuccessful execution without the proper manifest attribute.
Let’s write a simple Java class with a main method:
public class AppExample {
public static void main(String[] args){
System.out.println("AppExample executed!");
}
}
To pack our example class to a JAR archive, we have to go to the shell of our operating system and compile it:
javac -d . AppExample.java
Then we can pack it into a JAR:
jar cvf example.jar com/baeldung/manifest/AppExample.class
Our example.jar will contain a default manifest file. We can now try to execute the JAR:
java -jar example.jar
Execution will fail with an error:
no main manifest attribute, in example.jar
3. Executing a JAR With the Main Manifest Attribute
As we have seen, JVM couldn’t find our main manifest attribute. Because of that, it couldn’t find our main class containing our main method.
Let’s include a proper manifest attribute into the JAR along with our code. We’ll need to create a MANIFEST.MF file containing a single line:
Main-Class: com.baeldung.manifest.AppExample
Our manifest now contains the classpath to our compiled AppExample.class.
Since we already compiled our example class, there’s no need to do it again.
We’ll just pack it together with our manifest file:
jar cvmf MANIFEST.MF example.jar com/baeldung/manifest/AppExample.class
This time JAR executes as expected and outputs:
AppExample executed!
4. Conclusion
In this quick article, we showed how to pack a simple Java class as a self-executing JAR, and we demonstrated the importance of a main manifest attribute on two simple examples.
The complete source code for the example is available over on GitHub. This is a Maven-based project, so it can be imported and used as-is.