Thinking In Java 4th Edition 关于javac的一点错误

  Bruce Eckel 的 Thinking In Java 第四版第149页中提到,他使用了package net.mindview.simple;语句,然后用javac 直接编译,出来的文件位于C:\DOC\JavaT\net\mindview\simple。作者继续解释道“

If you walk back through this path, you can see the package name net.mindview.simple,
but what about the first portion of the path? That’s taken care of by the CLASSPATH
environment variable, which is, on my machine:
CLASSPATH=.;D:\JAVA\LIB;C:\DOC\JavaT

  言下之意是,因为ClassPath所以编译出的class文件才会在C:\DOC\JavaT目录下。

  但是由此我产生了疑问,我在F:/learningJAVA/mypackage目录下,放置了一个MyClass.java,其第一行命令是package mypackage;。第一次,我的Classpath包含 . (即当前目录),我进入到F:/learningJAVA/mypackage执行javac MyClass.java 结果编译出来的class在Class存放目录(F:/learningJAVA/mypackag)下。第二次,我把Classpath 的 . 去掉了,再次编译,结果一样。第三次,我在F:目录下,执行javac F:/learningJAVA/mypackage/MyClass.java, 编译出来的结果再次一样。

  第四次,我把MyClass.java文件移动到F:/learningJAVA/目录下,执行javac F:/learningJAVA/MyClass.java 结果不一样了,编译出来的F:/learningJAVA/下出现了mypackage文件夹,里面有了MyClass.class文件。

  由此,我得出结论,如果javac中没有使用-d 项,编译器所做的工作是,首先看所编译的java档存放的目录与其中的package命令是否一致,如果一致(比如我的MyClass.java是在mypackage目录下的,与package mypackage命令位置一致)则直接在java档所在目录放置编译出的class挡。如果不一致,则在java档所在目录下,产生package命令指定的文件夹,在其中放置class档。

  另外,我查了Oracle的javac documentation,发现这么一段:

-ddirectorySet the destination directory for class files. The directory must already exist; javac will not create it. If a class is part of a package, javac puts the class file in a subdirectory reflecting the package name, creating directories as needed. For example, if you specify -d C:\myclasses and the class is called com.mypackage.MyClass, then the class file is called C:\myclasses\com\mypackage\MyClass.class.

If -d is not specified, javac puts each class files in the same directory as the source file from which it was generated.

Note: The directory specified by -d is not automatically added to your user class path.

  和上面的实验结果一致。If a class is part of a package, javac puts the class file in a subdirectory reflecting the package name, creating directories as needed。这一句是关键。

  然后我在另外一个网页下找到这么一些描述:

Note that the -d and -classpath options have independent effects. The compiler reads only from the class path, and writes only to the destination directory. It is often useful for the destination directory to be on the class path. If the -d option is not specified, the source files should be stored in a directory hierarchy which reflects the package structure, so that the resulting class files can be easily located.

  其中说到 -d 和 -classpath 指令是互不干涉的,编译器读取的时候会在乎 -classpath,写的时候会在乎 -d 。 虽然-classpath 和 系统的环境变量 CLASSPATH 还是有区别的。但是我推测,编译器把编译出来的class放在哪,与环境变量CLASSPATH无关。

posted on 2013-05-19 10:22  ZenLearner  阅读(194)  评论(1)    收藏  举报

导航