// shall I write some keywords here to boost search engine ranking?

Thursday, March 20, 2008

Classpath Explained

Classpath is one of the basic and yet confusing topic for many Java developer. I had spend some time to do some google and below is some of my summaries:

1. Classloading Sequence
Java load the classes with the sequence of: Bootstrap classes -> Extension classes -> User classes.

Bootstrap classes is the Java platform core classes such as rt.jar. Extension classes is the JAR file found in extension folder, normally JAVA_HOME/jre/lib/ext/. User classes is all the classes or JAR file set in the CLASSPATH.

2. Sequence does matter
When setting CLASSPATH, the sequence does matter. Java locate class file according to sequence of path/jar file in CLASSPATH. For example below:

set CLASSPATH=bin/;lib/MyJar.jar;.;

If bin/ and MyJar.jar contains the class file of same name (include package name), the class in bin/ will be load. If Bootstrap classes or Extension classes contains class of same name, it will have higher priority to be loaded.

3. Executable JAR file, the Good and Evil
Executable is convenient where you may just specify the main class of you application, and distribute it as a JAR file. And start it up by just double click the JAR file.

However, if you are to start you application with "java -jar MyJar.jar", all the user CLASSPATH will be ignored. Include the -cp and --classpath option in your java launcher command. The executable JAR file, and the classpath specified in the MANIFEST file will be the only place to search for user classes.

This also means that your program that load properties file from classpath will failed to locate the file. Unless you jar the properties file into the executable JAR file itself.

For example, if your program use log4j and it load configuration from default file 'log4j.properties', you need to add the log4j.properties into the JAR file inorder for log4j to locate it.

References & Further Reading

No comments: