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:
java -classpath C:\hello\build\classes com.javahowto.test.HelloWorld
-cpJVM option, a short form of
java -cp C:\hello\build\classes com.javahowto.test.HelloWorld
java -Djava.class.path=C:\hello\build\classes com.javahowto.test.HelloWorld
- Use current directory as the default classpath:
- Package all classes into a self-containing jar file that has this in its
Note: when you run java with
java -jar hello-world.jar
-cpoptions, or CLASSPATH environment variable are ignored, as JVM thinks all classes are already contained inside the jar file, or referenced via the Class-Path entry in its META-INF/MANIFEST.MF.
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.pathin 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