Java - Classpath variable

> Procedural Languages > Java

1 - 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 ???)

Advertising

3 - Management

3.1 - 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:

3.1.1 - 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 

3.1.2 - 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.

3.1.3 - Manifest file

in a manifest file

Class-Path: lib/supportLib.jar lib/supportLib2.jar
Advertising

3.2 - Add

3.2.1 - 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

3.2.2 - 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

3.3 - Get

Java - System Property

System.getProperty("java.class.path")
Advertising

4 - Snippet

4.1 - 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

5 - Support

5.1 - You cannot use both -jar and -cp on the command line

6 - Documentation / Reference

lang/java/classpath.txt · Last modified: 2018/12/19 20:31 by gerardnico