Friday, June 18, 2010

Executable Jars

Languages like .NET and C++ have historically had the advantage of being OS-friendly, in that simply referencing their name at the command-line (helloWorld.exe) or double-clicking their icon in the GUI shell would launch the application. In Java programming, however, a launcher application — java — bootstraps the JVM into the process, and we have to pass a command-line argument (com.tedneward.Hello) indicating the class whose main() method we want to launch.

These additional steps make it harder to create user-friendly applications in Java. Not only does the end user have to type all of these elements at the command-line, which many end users would rather avoid, but chances are good that he or she will somehow fat-finger it and get an obscure error back.

The solution is to make the JAR file "executable" so that the Java launcher will automatically know which class to launch when executing the JAR file. All we have to do is introduce an entry into the JAR file's manifest (MANIFEST.MF in the JAR's META-INF subdirectory), like so:


Listing 2. Show me the entrypoint!
Main-Class: com.tedneward.jars.Hello



The manifest is just a set of name-value pairs. Because the manifest can sometimes be touchy about carriage returns and whitespace, it's easiest to use Ant to generate it when building the JAR. In Listing 3, I've used the manifest element of the Ant jar task to specify the manifest:


Listing 3. Build me the entrypoint!












All a user has to do to execute the JAR file now is specify its filename on the command-line, via java -jar outapp.jar. In the case of some GUI shells, double-clicking the JAR file works just as well.