Thursday, July 12, 2012

How to Use the Main-class JAR Attribute?

If you do package up an application in a JAR, there are two ways to run it. The first way is kind of clumsy--you have to add the JAR to your CLASSPATH and you have to know the name of the class to run. Suppose, for example, that I have an application called Shorts, packages in a JAR called Shorts.jar. To run it, I'd do something like this:
java -cp Shorts.jar Shorts
A much nicer solution is to use the Main-class attribute, which is a way of embedding the name of the class to run inside the JAR. Then you can just run the application (in Java 2, at least) like this:
java -jar Shorts.jar
How do you do it? Normally, you would create the JAR something like this: jar cvf Shorts.jar *.class
The trick to adding the Main-class attribute is defining an entirely separate file with the attribute definition. For instance, create the following one-line file and save it as
Main-class: Shorts
Now, to create the JAR, use this command line:
jar cvmf Shorts.jar *.class
The m option reads information from the file you just created and adds it to the manifest of the JAR you're creating. Now you can run the JAR using java -jar Shorts.jar.

No comments:

Post a Comment