01 April 2011

Bulldozing Java's classpath system to just make stuff work.

If you use Java, then you'll know it has this horrible (in my view) classpath concept, which usually just means more work to get something running (again in my experience.)

I came across this problem the other day when trying to run someone else's code, which was arranged neatly into projects, packages etc., each of which built to a separate .jar file in its own subdirectory... ugh. (In case you haven't realised yet, I don't much like Java!)

Anyway, yesterday I stumbled upon this little nugget, which makes running something structured like this a breeze.

First, stick this line in a script in the root directory of the Java project:

find . -name '*.jar' | tr '[:space:]' ':' | sed -e 's/:$//g' > classpath

which finds all the .jar files in any subdirectory, lists them, formats them suitably for Java to understand and sticks them in the file "classpath".

Second, run the program like this, using the newly generated "classpath" file to tell the virtual machine where to look:

java -cp `cat classpath` example.Main

Thanks to Cefn Hoile for the tip!

Categories: All articles Java