Main-Class Attribute in Modular JARs
What you'll learn: How to specify and launch the main entry point of a modular JAR using the manifest's Main-Class attribute and module-aware launch commands.
Understanding the Main-Class in Modular Context
In traditional JAR files, the Main-Class attribute in the manifest tells the JVM which class contains the main() method to execute. This attribute continues to work in modular JARs, but now you have two ways to launch your application: the traditional classpath approach and the module-aware approach.
When you create a modular JAR with a module-info.java, you can still embed the Main-Class attribute in the JAR's META-INF/MANIFEST.MF file. This allows flexibility in how users run your application.
Setting the Main-Class Attribute
When using the jar tool to create your modular JAR, specify the main class with the -e or --main-class option:
jar --create --file myapp.jar --main-class com.myapp.Main -C classes .
This embeds Main-Class: com.myapp.Main in the manifest.
Launching the Modular JAR
Option 1: Using -m or --module:
java --module-path myapp.jar --module com.myapp/com.myapp.Main
Or with the shorthand that uses the manifest's Main-Class:
java --module-path myapp.jar --module com.myapp
Option 2: Direct JAR execution (if Main-Class is set):
java -jar myapp.jar
The module system recognizes the main class from the manifest and launches it within the module context, maintaining strong encapsulation.
Why This Matters
The Main-Class attribute bridges traditional JAR execution with the module system, providing backward compatibility while enabling modular benefits like explicit dependencies and strong encapsulation at runtime.
Key Takeaway: The Main-Class attribute in modular JARs lets you launch applications using java -m module.name (with or without specifying the class) or java -jar, seamlessly integrating module-aware execution with familiar JAR conventions.