6 Ways of Setting Java Classpath

How to set Java classpath? List as many ways as you can. This can be an interesting Java job interview question. Here are what I came up with:

  1. Use -classpath JVM option:
    java -classpath C:\hello\build\classes com.javahowto.test.HelloWorld
  2. Use -cp JVM option, a short form of -classpath:
    java -cp C:\hello\build\classes com.javahowto.test.HelloWorld
  3. Use -Djava.class.path system property:
    java -Djava.class.path=C:\hello\build\classes com.javahowto.test.HelloWorld
  4. Use CLASSPATH environment variable:
    set CLASSPATH=C:\hello\build\classes;
    java com.javahowto.test.HelloWorld
  5. Use current directory as the default classpath:
    cd C:\hello\build\classes;
    java com.javahowto.test.HelloWorld
  6. Package all classes into a self-containing jar file that has this in its META-INF/MANIFEST.MF.
    Main-Class: com.javahowto.test.HelloWorld
    java -jar hello-world.jar
    Note: when you run java with -jar option, any -classpath, or -cp options are ignored, as JVM thinks all classes are already contained inside the jar file.
Among all those options, I usually use option 1, and occasionally 6. I don't like my Java apps have dependency on environment settings like CLASSPATH, which is totally unpredictable. Using current directory as the default classpath is not a good idea either, since your classes may be scattered in several directories, folders and jar files.

Can I set classpath at java runtime dynamically and programmatically? No. Although you can set the system property java.class.path in your application, but its new value doesn't affect the system classloader. If you need to reset classpath, it's time to consider using a custom classloader as the child loader of the system classloader.

With a custom classloader, you have full control where to load class files, from local file system, remote url, or even database. Classes loaded by such a custom loader are only visible by this loader and its child loaders, but not to its parent loader nor the system classloader.

For the same reason, you can't dynamically set minimum/maximum heap size of a JVM. These JVM options are all set once when JVM is started and unchanged throughout its life.

JDK 6 now support * in classpath, so you can include all jar files in a directory to the classpath easily. But you may run into problems described in http://javahowto.blogspot.com/2006/07/jdk-6-supports-in-classpath-but-be.html


Followers

Pageviews Last 7 Days