Jun 9, 2011

Java simple rule to avoid trouble

As troublesome as the classpath is, you can tame it with a few simple rules. In particular:
Place every class in a package.
Rigorously follow package and class naming and capitalization conventions.
Make sure your package hierarchy matches the directory hierarchy.
Always use the -d option to javac.
Never put anything in jre/lib/ext.
Never put anything in jre/lib/endorsed.
Never put .java files in the same directory as .class files.
Never put any .java or .class files in the current working directory.

One final tip: A lot of time-killing problems with the classpath revolve around simple errors like misspelling a directory name or compiling from the wrong directory. If you just can't figure out what's going wrong, ask a friend or colleague to look at your problem. Often I find I'm too close to the problem to see a bug in my setup that's immediately obvious to anyone else. A second pair of eyes is a very effective debugging technique.

The classpath is certainly not easy, but there is a method to its madness and it is manageable. A bit of care and some attention paid to naming conventions, command-line arguments, and directory structures should enable you to compile and run programs with a minimum of fuss.

Reference 1

No comments:

Orpheus and Eurydice