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.
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
By setting the CLASSPATH environment variable in a command line
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.
In a manifest file
Class-Path: lib/supportLib.jar lib/supportLib2.jar
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
- 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?
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