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