This section provides a tutorial example on how to use the '-classpath' option to specify the class path for the 'javac' tool to load any classes required during the compilation.
The most commonly used "javac" option is "-classpath", which specifies a list of path names where the compiler will search for compiled type definitions.
If "-classpath" is not specified, the current directory will be used as the class path.
When compiler encounters an unknown type in the source file, it will try to find the type definition by searching
class files in the class path.
To experiment how the compiler uses "-classpath", I wrote the following simple source file, EchoerTest.java:
/**
* EchoerTest.java
* Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
*/
public class EchoerTest {
public static void main(String[] a) {
Echoer e = new Echoer();
e.setReq("Hello world!");
System.out.println(e.getRes());
}
}
When I tried to compile this source file, I got the following error:
C:\herong>javac EchoerTest.java
EchoerTest.java:7: cannot resolve symbol
symbol : class Echoer
location: class EchoerTest
Echoer e = new Echoer();
As you can see, the compiler failed to find the definition for the type "Echoer".
In order to help the compiler to find the missing type definition, I wrote the following source
code for the Echoer class, Echoer.java:
/**
* Echoer.java
* Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
*/
public class Echoer {
private String req = null;
private String res = null;
public void setReq(String r) {
req = new String(r);
char[] a = r.toCharArray();
int n = a.length;
for (int i=0; i<n/2; i++) {
char t = a[i];
a[i] = a[n-1-i];
a[n-i-1] = t;
}
res = new String(a);
}
public String getRes() {
return res;
}
}
Then I compiled the Echoer.java and provided Echoer.class to the class path to compile EchoerTest.java: