June 20, 2023

Java on Fedora - a JAR file

Without a doubt, we are getting ahead of ourselves. But with that warning, we forget boldly onward.

What would a person do if they had a java application with 30 or 40 java files (and hence class files). How would they distribute it? Presumably this is where ".jar" files come in.

Indeed there is a jar utility and you use it to create "jar" files.
I did this, and it seemed to work:

jar -cvf MyCounter.jar MyCounter.class Pickle.class
But when I try to run it, I get this:
java -jar MyCounter.jar
no main manifest attribute, in MyCounter.jar
I search on this and the prescription is to create a directory "META-INF" and within it a file "MANIFEST.MF" with contents:
Main-Class: MyCounter
This tells java which class it should hunt for a "main" method in. At this point things are getting complex enough that I create a Makefile:
all:  MyCounter.jar

MyCounter.jar: MyCounter.class Tester.class Pickle.class
	jar -cmvf META-INF/MANIFEST.MF MyCounter.jar MyCounter.class Tester.class Pickle.class

MyCounter.class: count.java Pickle.class
	javac count.java

Pickle.class: pickle.java
	javac pickle.java

clean:
	rm -f *.jar *.class
I'll not that there are two unusual things going on. One is that when we compile "count.java" we get two class files (MyCounter and Tester). This is something you don't see when compiling C code for example. The other odd thing is that we must compile "pickle" before we try to compile "count" or it complains that it cannot find the Pickle class. This is something else we don't see with other languages. Perhaps these odd aspects of Java explain why there seem to be Java specific build tools.

Also it seems clear that the "MANIFEST" could have other information (maybe lots of other information). People using build tools usually push a button to generate a jar file and the MANIFEST is automatically generated for them. But the above Makefile does work and we can just type "make" to get our jar file. And we run the jar file via:

java -jar MyCounter.jar
And it runs just fine.
Have any comments? Questions? Drop me a line!

Adventures in Computing / [email protected]