Re: Question on jars
On 03/23/2011 06:43 PM, Anonymous wrote:
hi everyone. I've been going thru a nice book trying to learn java and the
book mentioned how to make a jar of classes and talked abit about classpath
and how you have to make directories matching the class names etc. So I
tried to create a jar of my classes but I can't compile against it. I am
getting errors about the class not being found even though verbose shows my
classpath is being used.
Are jars meant to be used this way in compiling code against packaged
classes or are jars just for executing? I've missed something here.
Yes, they are, for both. But no doubt you missed some tiny detail of how to
There are a lot of classpath interactions with file systems and JAR structures.
Think of package dots (".") as cognate to directory slashes ("/").
That's the directory structure. What goes into directories? Files! What
goes into packages? Types! (Classes and interfaces)
Notice that I give you relative paths here. "com/" relative to what? On the
package side, it's a meaningless question - it corresponds to the root of all
packages, the "default" (unnamed) package.
So really, we have:
But that just begs the same question - what is the root?
The root is some part of the classpath. The classpath specifies a bunch of
roots, and the JVM searches each one in turn trying to satisfy a "load" command.
So suppose you have directories in a file system, and your classpath starts at:
so really, 'Foo' is loaded from
This part drove me nucking futs when I was first learning Java.
Now, what's a classpath for this example?
$ java -cp /opt/applications/lewscanon:. \
The classpath is the cited "lewscanon" directory first, followed by "."
Clearly, for this example 'com.lewscanon.someapplication/module.Foo' is a main
class. It is found relative to the first root of the classpath.
JARs? You want to know about JARs? Well, a JAR can root a classpath, too.
$ java -cp someapplication.jar \
This time I left out the ".", because there's no sense in finding the main
class in the JAR if I'm looking in my current directory. YMMV.
Now the JAR is the root of a classpath. But what's inside the JAR? Look with
your favorite unzip utility (for example, "jar"):
$ jar -tf someapplication.jar
The internal directory structure corresponds to what should be at the root of
But, wait! There's more! If you set up that magic "META-INF/MANIFEST.MF"
correctly (RTFM for details), then you can indicate the "Main-Class:" so that
the JAR system finds it automatically, and all "Class-Path:" specifications
come from within the JAR (ignoring the command line).
$ java -jar someapplication.jar
$ cat /opt/applications/lewscanon/someapplication/src/conf/MANIFEST.MF
Class-Path: log4j.jar postgresql-9.0-801.jdbc4.jar eclipselink.jar
eclipselink.jar log4j.jar postgresql-9.0-801.jdbc4.jar someapplication.jar
So yes, a JAR can provide a library or package an executable.
Honi soit qui mal y pense.