Monday 10 June 2019

Exploring CLASSPATH


‘CLASSPATH’ tells java applications, where to look for java classes.

CLASSPATH variable
If you set the CLASSPATH variable to one or more paths, then Java classloader looks for the needed classes in these paths.

Let me explain with an example.
Create App.java file under the directory com/sample/app.

$tree
com
└── sample
    └── app
        └── App.java

2 directories, 1 file


Compile App.java.
$javac com/sample/app/App.java
$
$tree com
com
└── sample
    └── app
        ├── App.class
        └── App.java

2 directories, 2 files

As you see, App.class file is created in com/sample/app folder.


Try to run App file.
$java com/sample/app/App
Error: Could not find or load main class com.sample.app.App

We got this error, since Java class loader do not know, from where to load the classes. You can solve this problem by setting CLASSPATH variable to the folder where 'com' folder is located.

For example
export CLASSPATH=/Users/krishna/Documents/TechnicalDocuments

If you are using Windows system, use below statement

SET CLASSPATH={path_to_com_folder}
$tree 
com
└── sample
    └── app
        ├── App.class
        └── App.java

2 directories, 2 files
$
$pwd
/Users/krishna/Documents/TechnicalDocuments
$
$export CLASSPATH=/Users/krishna/Documents/TechnicalDocuments
$
$java com/sample/app/App
Hello World

Can I set multiple folder paths to classpath?
Yes you can set multiple folders to classpath by separating them by : in linux, ; in Windows.

Example
export CLASSPATH=/Users/krishna/Documents/tutorial;/Users/krishna/Documents/examples;


Set the classpath at the application level

Using -cp option, you can specify the classpath.
$java -cp /Users/krishna/Documents/TechnicalDocuments com.sample.app.App
Hello World
$
$java -cp /Users/krishna/Documents/TechnicalDocuments com.sample.app/App
Hello World
$
$java -cp /Users/krishna/Documents/TechnicalDocuments com.sample/app/App
Hello World
$
$java -cp /Users/krishna/Documents/TechnicalDocuments com/sample/app/App
Hello World

When you set the variable CLASSPATH, it is available for all the applications. All the application look for the folders set in CLASSPATH variable to load the classses. Some cases it may lead to chaos, for example, in one application you are using gson library 1.1, but in other you are using gson library 2.2. When the classloader tries to load gson classes, it will load whichever it enocounter in the path first. So it is always better to use application specific classpath.

Reference



Previous                                                 Next                                                 Home

No comments:

Post a Comment