Java - Classpath variable
Table of Contents
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 different file system directories specified in the CLASSPATH variable to resolve references to the classes needed for execution.
The -jar option of java disables the use of CLASSPATH. See Java - Jar (Startable|Runnable|Executable) (True ???)
Articles Related
Management
Set
Do not put quotes, trailing backslash in the CLASSPATH, even if there is a space in a path directory
The class path can be set using either the:
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
C:> 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
Add
Class
You need to add the directory root of the class definition.
Example for the class <wrap box>utility.myapp</note> located in the directory <wrap box>c:\java\MyClasses\utility\myapp</note>, you need to add the directory <wrap box>c:\java\MyClasses\</note>
java -classpath C:\java\myClasses utility.myapp.Cool
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
Get
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
Documentation / Reference
- Setting the Classpath: Solaris and Linux - Windows