Monday, May 26, 2008

Compiling Java Code without the woes of a classpath

Hello World!
Eclipse and other IDEs’ are a great tool for developing, testing and deploying Java applications and save you the trouble of explicitly writing out commands and statements for compilation, which you'll usually have to type in every time if developing from a simple text editors and command line compilers and interpreters. However, often there has been a need or constraint when you cannot use eclipse for compiling and executing purposes always. Let's say you write a neat piece of code involving classes spread across number of different jars. Now you want to move it to, say, a UNIX environment where it may be required that the class be recompiled and executed manually over command-line for testing. Typically, somebody would've taken the pains to write out an ant script or a build script which would set the class path variable for you, but if the class path is changing quite often due to reasons like (project is still under development) or if the build script is unavailable, it becomes a pain for the developer to type in the name of each and every jar explicitly in his class path every time he needs to compile or execute his code.
However, there is a shortcut to save you from the woes of typing in the class path every time especially when you're in a rush to get things done. You can use the java.ext.dirs argument with your other standard JVM arguments. When used, this option will pick up all the jars under the locations pointed out by this environment, without you have to explicitly mentioning each of the jar file names and location in your class path. Here's an example:
java -Djava.ext.dirs=/usr/j2sdk1.4.2_13/jre/lib:/user/user1/myJars -classpath /user/user1/appln/WEB-INF/classes MyClass
However, this should be used only for development purpose and as a short-cut and not as a standard practice. The right way in the end is to specify all the jars in your class path. The simple reason is that maybe during development you may use a jar and have the backup of the same jar also in one of the pointed locations by java.ext.dirs. As per Java specifications: "The rule of class loading clearly states that once an appropriate class is found no further searching is done. The class which is found (lexically) first is used. This is why you can change the name of two jars in the same directory which contain different versions of same class files and the classes in the jar which is lexically first will be used." So while using java.ext.dirs, you won't be able to control which jar to be picked up by java.
(Special thanks to Diloob for pointing this out and for extensive experimenting with this option.)