| • Articles • articles about computing
Mastering the Java classpaththe significance of the Class search path
An understanding of the Class search path is important for all Java developers. however, the widespread use of integrated development tools has concealed the technicalities for so long that there is a widespread lack of comprehension, even among experienced
Developers. The problem is particle ly acute with development of distributed applications, as the system which will run the application is likely to be configured rather differently from the one on which development takes place.
This article describes in detail how the Java compiler and the JVM use the Class search path to locate classes when they are referenced by other Java code. it does this with reference to a very simple example, which uses two classes in the same package.
We will see how varous operations to compile these two classes succeed and fail, depending on the class path setting.
To make things absolutely clear, we will use only simple command-line tools to carry out of the compile operations. interactive Development tools have their own ways of manipulating the class path, which vary from product to product.
There is no fundamental difference between the way that the Java compiler searches for classes, and the way that the JVM does it at run time. however, the compiler has the ability to compile classes from source code, where the JVM does not. in the examples
Below we will use the compiler, but similar issues apply at run time. The example
This example has two trivial classes:com.web_tomorrow.CPTest1Andcom.web_tomorrow.CPTest2, Which are listed below.
package com.web_tomorrow;public class CPTest1{public static void main(String[] args) { System.out.println ("Run CPTest1.main()"); }}package com.web_tomorrow;public class CPTest2{public static void main(String[] args) { System.out.println ("Run CPTest2.main()"); CPTest1 cpt1 = new CPTest1(); }}
One of the most fundamental rules of Java code organization is that 'package name = directory name '. we will begin by setting up a directory structure that matches the package assignment of these two classes. the classes are in a packagecom.web_tomorrow,
So we must create the Directorycom/web_tomorrowTo contain the source code.
[root] com web_tomorrow CPTest1.java CPTest2.java
In this document I will use the notation[root]' to mean Whatever directory contains the structure described abve ', that is, the root of the Directory layout. This will vary, of course, according to how you install the files. Basic Principles
Let's try to compileCPTest1.javaOn its own using the command-linejavacProgram. to disable the Class search path completely (so any existing setting does not interfere with the example), we can runjavacWith the option
'-classpath ""'.
As a first attempt, let's change directory to the locationCPTest1.java, And try to compile it by specifying its name onjavacCommand line.
cd [root]/com/web_tomorrowjavac -classpath "" CPTest1.java
This operation succeeds, because the compiler is able to findCPTest1.java(It is in the working directory), and becauseCPTest1Does not reference any other classes. The output file,CPTest1.classEnds up in the same
DirectoryCPTest1.javaBecause, again, you haven't given the compiler information to do anything else. So far so good. Now let's try the same thingCPTest2. Still in the 'web _ tomorrow' directory, execute this command:
javac -classpath "" CPTest2.java
This operation showould fail, even though the directory is the same as the previous step, andCPTest1AndCPTest2Are in the same package. The error message will be something like this:
PTest2.java:7: cannot resolve symbolsymbol : class CPTest1 location: class com.web_tomorrow.CPTest2 CPTest1 cpt1 = new CPTest1(); ^
The difference between this case and the previous, successful, one is thatCPTest2Contains a referenceCPTest1:
CPTest1 cpt1 = new CPTest1();
What is going on here? When the compiler encounters the referenceCP1TestHere, it assumes that this is a class in the same packageCP2TestThat is currently compiling. This is a correct assumption. So the compiler needs
Findcom.web_tomorrow.CP1Test. But it has nowhere to look, as we have explicitly set the Class search path to "" (I. e., nothing ).
You might think this problem can be resolved by telling the compiler to look in the current directory. the standard symbol for 'current directory' is a single period (.) in both UNIX and Windows systems. so try something like this:
javac -classpath "." CPTest2.java
This fails in exactly the same way as the previous example. The problem now is that althoughCPTest1.javaIs in the current directory, the class that it implements is not justCPTest1,com.web_tomorrow.CPTest1.
Compiler will look for a directorycom/web_tomorrow BelowThe current directory. So, overall, it is looking for a Java source or class file in the directory[home]/com/web_tomorrow/com/web_tomorrowWhich, of course, does not
Exist.
To make this compile operation work, we need to make the Class search path reference not the directory containingCPTest1, But a directory root from whichCPTest1Can be located by the compiler following the standard Java 'package
Name = directory name 'rule'. This shoshould work, although it's rather uugly:
javac -classpath "../.." CPTest2.java
Before seeing how we can make this less uugly, consider this example (still in the same directory ):
javac -classpath "" CPTest1.java CPTest2.java
This also works, even though the class path is empty. this is because the Java compiler will look for references between any source code explicitly listed on the command line. if there are named classes, all in the same directory, we can simplify this:
javac -classpath "" *.java
The '*. java 'pands to a list of all. java files in the current directory. this explains why Compiling Program Files in one operation often succeeds where attempts to compile a single file fails.
A more convenient way to compileCPTest2On its own is like this:
cd [root]javac -classpath "." com/web_tomorrow/CPTest2.java
In this example we specify the full pathCPTest2.java, But include '.' In-classpathOption. Again, we aren't telling the compiler to look for files in the current directory, we are telling itBegin a Class searchFrom
The current directory. Because the class we are looking for iscom.web_tomorrow.CPTest1, The compiler will search in./com/web_tomorrow(That is, the directorycom/web_tomorrowBelow the current directory). This is exactly
WhereCPTest1.javaIs located.
In fact, even though I only specifiedCPTest2On the command line, this practice does in fact lead to the compilationCPTest1As well. The Compiler finds.javaFile in the right place, but it can't tell whether
This Java source really implements the right class, so it has to compile it. But note that if we do this:
cd [root]javac -classpath "." com/web_tomorrow/CPTest1.java
It does not cause a compilationCPTest2.java, Because the compiler does not need to know anything aboutCPTest2To compileCPTest1. . Class files separate from. java files
The examples described so far, when successful, place the output.classFiles alongside.javaFiles from which they were generated. This is a simple scheme, and very widely used. However, developers like to keep the source
Tree free of generated files, and must therefore tell the Java compiler to maintain separate directories.classFiles. Let's see what impact this has on the class search path.
To begin we will need to delete any.classFiles lurking around after the previous examples. We will also contain a new directoryclassesTo contain the generated.classFiles. The procedure at the command line wowould
Be something like this:
cd [root]rm com/web_tomorrow/*.classmkdir classes
Don't forget to swap the '/'characters for' \ 'if you are using a Windows system. The directory structure now looks like this.
[root] com web_tomorrow CPTest1.java CPTest2.java classes
Let's compileCPTest1.java, SpecifyingclassesAs the destination directory (using-dOption ):
cd [root]javac -d classes -classpath "" com/web_tomorrow/CPTest1.java
This shoshould succeed, but you shoshould notice that.classFiles have not been placed intoclassesDirectory at all. Instead, we have a new directory structure like this:
[root] com web_tomorrow CPTest1.java CPTest2.java classes com web_tomorrow CPTest1.class
What has happened is that the compiler has created a directory structure to match the package structure. It has done this to be helpful, as we shall see. When we come to compileCPTest2.javaWe have two choices. First, we can compile it as described
Above, allowing the compiler to compileCPTest1As part of the process. Alternatively, We can compile it and use-classpathOption to refer to the compiler to.classFile generated in the previous step. This method
Is superior, as we don't have to repeat the compilationCPTest1.
cd [root]javac -d classes -classpath classes com/web_tomorrow/CPTest2.java
By doing this, we end up with this directory structure.
[root] com web_tomorrow CPTest1.java CPTest2.java classes com web_tomorrow CPTest1.class CPTest2.class
Of course we cocould have compiled both.javaFiles in the same command, and got the same result. Jars on the classpath
The Java compiler and run-time can search for classes not only in separate files, but also in 'jar' archives. A jar file can maintain its own directory structure, and Java follows exactly the same rules as for searching in ordinary directories. specifically,
'Directory name = package name '. because a jar is itself a directory, to include a jar file in the class search path, the path must reference the jar itself, not merely the directory that contains the jar. this isVeryCommon error. Suppose I have
A jarmyclasses.jarIn directory/myclasses. To have the Java compiler look for classes in this jar, we need to specify:
javac -classpath /myclasses/myclasses.jar ...
And not merely the Directorymyclasses. Multiple Class search directories
In the examples above, we have toldjavacTo search in only one directory at a time. In practice, your class search path will contain in numerous directories and jar archives.-classpathOptionjavacAndjavaAllows
Multiple entries to be specified, but notice that the syntax is slightly different for UNIX and Windows systems.
On UNIX, We wocould do this:
javac -classpath dir1:dir2:dir3 ...
Whereas on windows we have:
javac -classpath dir1;dir2;dir3 ...
The reason for the difference is that Windows uses the colon (:) character as part of a filename, so it can't be used as a filename separator. naturally the directory separator character is different as well: forward slash (/) for UNIX and backslash (\)
Windows. System classpath
Rather than specifying Class search path onjavacCommand line, we can make use of a 'system' class path. this is the class path that will be used by both the Java compiler and the JVM in the absence of specific instructions to the contrary.
In both UNIX and Windows systems, this is done by setting an environment variable. For example, in Linux withbashShell:
CLASSPATH=/myclasses/myclasses.jar;export CLASSPATH
And in Windows:
set CLASSPATH=c:\myclasses\myclasses.jar
This procedure is fine for short-term changes to the system classpath, but if you want these changes to be persistent you will need to arrange this yourself. details vary from system to system. on a Linux system, for example, I wocould put the commands in
File.bashrcIn my home directory. on Windows 2000/NT There Is A 'control panel 'page for this.
Setting the system classpath is a useful procedure if you have jars full of classes that you use all the time. for example, if I am developing Enterprise JavaBean (EJB) applications using sun's J2EE 'reference implementation', all the EJB-related classes
Are in a jar called'j2ee.jar'That comes with the distribution. I want this jar on the class search path all the time. in addition, most people want to ensure that the current directory is on the search path, whatever the current directory happens
To be. So in my.bashrcFile I have this line:
CLASSPATH=/usr/j2ee/j2ee.jar:.;export CLASSPATH
Where.' indicates Current directory '.
It is easy to overlook that-classpathOption on the command lineReplacesThe default, system class path; it does not add to it. So what shoshould I do if I want to set the class path to include the default system classpathPlusSome
Other entries? I cocould simply use-classpathOption and list the default entries in addition to my extras. However, a better way is to reference the classpath environment variable. The syntax for this is different-of course-on Windows
And Unix systems. On Unix:
javac -classpath $CLASSPATH:dir1:dir2 ...
Where$CLASSPATHExpands to the current setting of the classpath environment variable. On Windows:
javac -classpath %CLASSPATH%;dir1:dir2 ...
Finally, please note that if directories in your class search path have spaces in their names, you may have to use double-quotes on the command line to prevent the classpath being split up. for example:
javac -classpath "%CLASSPATH%";dir1:dir2 ... |