简体   繁体   中英

Do not understand following use of -classpath by javac

I am not very clear with the following question from SCJP Book (I read the solution and explanation though) ..

Consider the following directory structure :-

foo --> test --> xcom --> A.class, B.java

Here foo, test and xcom are directories. A.class and B.java are the files in xcom directory.

Following are the source codes of corresponding files:-

A.java

package xcom;
public class A { }

B.java

package xcom;
public class B extends A { }

The default classpath is /foo.

Now, in order to compile B.java, I keep my current directory as test and give :-

javac -classpath xcom xcom/B.java

Here I give the classpath as xcom which has A.class. But still it does not find class A. Why is it so??

If your classes are in package xcom, then your classpath needs to be at the directory directly above that. In this case, the classpath should be foo/test.

And if your current directory is foo/test , then this should be your javac:

javac -classpath . xcom/B.java

Because you have to specify classpath root to -classpath argument, like javac -classpath . xcom/B.java javac -classpath . xcom/B.java . To compile class B java compiler requires class A, it tries to locate class A file in {classpathroot}/xcom/ .

Note: . - is a current directory

I think the root cause here is a misunderstanding of a "fully-qualified name" in Java.

The fully-qualified names of your two classes are xcom.A and xcom.B. Their source is in files A.java and B.java in a directory named xcom; the fully-qualified names dictate the directory structure. When you are going to use the files, either to compile them or run them, the classpath contains one or more locations from which the fully-qualified names can be found; so java is looking for xcom\\A.java and xcom\\B.java (when compiling) and xcom\\A.class and xcom\\B.class (when running).

That is why the classpath needs to specify the directory that contains xcom.

As you progress to more complex environments: the classpath can be a list of such locations; each location is separated by a semicolon on windows and a colon on unix systems. Each location can be a directory, as you've already seen, but it can also be a jar file. jar files are in zip file format, and zip files have a directory structure just like disks do. So you could zip up your class files, maintaining their xcom parent (but not their full paths), and specify the jar file in the classpath instead of a directory.

I know the question was already answered somewhat, but thought you might like the background explanation as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM