Building an executable jar with Ant

An executable jar file has a defined default class, allowing the default class to be invoked without explicitly identifying it via the command line. On a supporting OS (such as Mac OS/X or Microsoft Windows), this allows the class to be invoked by double-clicking the file.

I know that making a jar file executable requires an entry in the manifest file. I can usually remember that the attribute in question is Main-Class (although I’m usually fuzzy about the proper capitalization). The problem is remembering the correct command line options to insert my own MANIFEST.MF file into a jar file. All in all, it is much simpler to add a manifest element and let ant handle it for me.

Let’s start with the example from my Ant Hello World Revisited. I’ve added a manifest element that specifies “hello” as the default class to be executed. Note that I’ve also designated the “jar” task as the default task.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ cat hello.xml
<project default="jar">
<target name="compile">
<javac srcdir="." />
</target>
<target name="jar" depends="compile">
<jar destfile="hello.jar"
basedir="."
includes="**/*.class">

<manifest>
<attribute name="Main-Class" value="hello" />
</manifest>
</jar>
</target>
</project>

As a reminder, here’s the java class:

1
2
3
4
5
6
7
$ cat hello.java
public class hello {
public static void main( String[] args )
{

System.out.println( "Hello World" );
}
}

Now we simply build our jar file:

1
2
3
4
5
6
7
8
9
10
11
$ rm *.jar
$ ant -f hello.xml
Buildfile: hello.xml

compile:

jar:
[jar] Building jar: /Tutorial/Ant/Jar/hello.jar

BUILD SUCCESSFUL
Total time: 2 seconds

And execute the default class by using the -jar command line option to java:

1
2
$ java -jar hello.jar
Hello World

Disclaimer: I don’t claim to be an expert on ant. Please send comments and corrections.