Java - What is the Classpath?
About
Java classes needed to execute a Java program can be physically located in different file system directories.
When Java classes are loaded, it searches a list of directories that are specified in what's called the classpath.
It's the same notion as the PATH environment variable for executable but for Java class.
Classpath and Executable Jar
Using the -jar option of java disables the use of CLASSPATH.
It means that you can't modify the classpath of excutable jar if you use the -jar option to execute it.
How can I set
Do not put quotes, or trailing backslash in the CLASSPATH, even if there is a space in a path directory
The class path can be set using one of this method.
JVM cp Options
- -classpath option (shortened -cp) when calling an SDK tool
sdkTool -classpath classpath1;classpath2...
The -classpath option is present in the following sdk (java, jdb, javac, and javah ). Example:
# Windows with ;
java -cp /directory/with/my/class;anotherDirToaJar path/To/MainClass
# Linux with :
java -cp /directory/with/my/class:anotherDirToaJar path/To/MainClass
Environment variable
By setting the CLASSPATH environment variable in a command line
set CLASSPATH=classpath1;classpath2...
Do not ever set CLASSPATH for the system. It only causes confusion and breaks things. In most development environments, it is best to temporarily set the CLASSPATH environment variable in the command line shell.
Manifest file
In a manifest file
Class-Path: lib/supportLib.jar lib/supportLib2.jar
How can I add
a Class?
You need to add the directory root of the class definition.
Example for the class utility.myapp located in the directory c:\java\MyClasses\utility\myapp, you need to add the directory c:\java\MyClasses\
java -classpath C:\java\myClasses utility.myapp.Cool
a Jar?
- Adding one jar
In an archive file (a .zip or .jar file) the class path entry is the path to and including the .zip or .jar file. For example, to use a class library that is in a .jar file, the command would look something like this:
java -classpath C:\java\myClasses\myClasses.jar utility.myapp.Cool
- Adding all JAR files in a directory (since Java 6)
REM Windows
java -classpath ".;c:\mylib\*" MyApp
echo Linux example
java -classpath '.:/mylib/*' MyApp
How can I get the classpath value?
System.getProperty("java.class.path")
Snippet
DOS: Building a classpath from a directory of library
@REM Appending additional jar files to the CLASSPATH...
IF EXIST %MY_DIR%\lib FOR %%G IN (%MY_DIR%\lib\*.jar) DO (CALL :APPEND_CLASSPATH %%~FSG)
echo %CLASSPATH%
java ....
:APPEND_CLASSPATH
SET CLASSPATH=%CLASSPATH%;%1
GOTO :EOF
Support
You cannot use both -jar and -cp on the command line
See http://docs.oracle.com/javase/1.5.0/docs/tooldocs/windows/java.html#-jar
Documentation / Reference
- Setting the Classpath: Solaris and Linux - Windows