Executable JARs and the Main-Class Attribute
What you'll learn: How to make a JAR file runnable by specifying which class contains your main method.
The Problem: Which Class Should Run?
You've learned how to create JAR files and understand the manifest file. But when you package multiple classes into a JAR, Java doesn't automatically know which one contains your main(String[] args) method. Should it run com.myapp.Application or com.myapp.Launcher? This is where the Main-Class attribute comes in.
Making a JAR Executable
To create an executable JAR, you must tell Java which class serves as the entry point by adding a Main-Class attribute to your manifest file.
Manifest syntax:
Main-Class: com.mycompany.myapp.MainApplication
Critical details:
- Use the fully qualified name (package + class name)
- The manifest file must end with a newline character
- There must be a space after the colon
Creating an Executable JAR
Step 1: Create a manifest file (manifest.txt):
Manifest-Version: 1.0
Main-Class: com.example.Calculator
Step 2: Build the JAR with this manifest:
jar cfm myapp.jar manifest.txt com/example/*.class
Step 3: Run it directly:
java -jar myapp.jar
No need to specify the class name—Java reads the manifest and launches the Main-Class automatically!
The Analogy
Think of it like labeling a toolbox: you might have many tools inside, but you put a big label on the outside saying "Main Tool: Hammer" so anyone opening it knows which tool is the primary one to grab first.
Key Takeaway: The Main-Class attribute in the JAR manifest tells Java which class to execute when you run java -jar, making your JAR file self-contained and executable.