Sunday, February 1, 2009

Classpath Gotchas

I still remember My First Java error on running a Simple HelloWorld.java example: -

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld

In few hours I managed to run my HelloWorld example by using -classpath but this was just the beginning.

And now after working a while in Java/j2EE and dealing with many ugly classpath issues, i want share few of my experiences.

-classpath
or -cp works as the same (-cp is available with java.exe and not javac.exe. in 1.5 it is available for both) and they include specified jars in your java classpath.

This approach has some drawbacks: -
1. you need to hard code the jar file names in your classpath
2. In windows there is a limitation of the size of the classpath which you can specify (Thank God our production boxes does not uses Windows as OS :))
3. Lastly you cannot specify "*" in your "classpath" directive (it doesn't recognize it. In JDK6 this has been resolved)

In order to solve the above issues you can easily use an ANT Script but i personally feel that using an ANT script for each and every thing is not a good idea.

There is an another parameter known as -Djava.ext.dirs=""

By default this parameter is pointed towards < JAVA_HOME>/jre/lib/ext and if you overwrite than it will pick the jars from the given location.
Also you can specify multiple locations separated by ";"

using "java.ext.dirs" also has its own limitation - you cannot specify "classpath" directive with the "java.ext.dir".

But if we give it a thought than I don't think its a limitation,

e.g Running any Java Example will involve either -cp or -classpath, it will not make sense to use both.
Same is the case with "java.ext.dirs", there should not be any need to specify classpath directive with "java.ext.dirs"

No comments: