javac如何自动编译一个类的依赖

2022-01-13 00:00:00 package import java javac

给定以下目录结构:

/top
   |--- wrk
          |--- pkg
                  |--- A.java
                  |--- B.java

假设A.javaB.java这两个文件分别包含以下代码:

Assume that the two files A.java and B.java contain the following code, respectively:

// Filename: A.java
package pkg;
class A { B b; }

// Filename: B.java
package pkg;
class B {...}

假设当前目录为/top/wrk

为什么命令 javac -cp .即使我们还没有编译 B.java,pkg/A.java 也能成功运行?

Why does the command javac -cp . pkg/A.java work successfully even though we have not yet compiled B.java?

另外,如果当前目录是 /top/wrk/pkg 那么命令 javac A.java 有效.怎么会这样?

Also if the current directory is /top/wrk/pkg then the command javac A.java works. How so?

推荐答案

为什么命令 javac -cp .即使我们还没有编译 B.java,pkg/A.java 也能成功运行

Why does the command javac -cp . pkg/A.java work successfully even though we have not yet compiled B.java

当你编译 A.java 时,编译器也会编译 B.java 因为 A.javaB.java 在同一个包中.即使 B.javaA.java 位于不同的包中(前提是 B 是公共的),只要这两个包都可以使用存在于 wrk 目录中,您从 wrk 目录编译 A.java.

When you compile A.java, the compiler will compile B.java as well since both A.java and B.java are in the same package. This will work even If B.java was in a different package from A.java (provided B is public) as long as both the packages are present in the wrk directory and you compile A.java from wrk directory.

来自 Oracle 文档 <代码>javac:

如果没有指定-sourcepath选项,也会在用户类路径中搜索源文件.

If the -sourcepath option is not specified, the user class path is also searched for source files.

来自 Oracle 文档 的 CLASSPATH

类路径的默认值为."

如果您没有设置 CLASSPATH,它将默认为 ..随后,sourcepath 也将是 .,因为默认的 sourcepathCLASSPATH 相同.您可以通过使用 javac -verbose -g pkgA.java 编译 A.java 来确认默认源路径设置为 ..请注意,编译器正在当前目录中查找 .java 文件:

If you haven't set a CLASSPATH, it will be defaulted to .. Subsequently, the sourcepath will also be . since the default sourcepath is the same as the CLASSPATH. You can confirm that the default sourcepath is set to . by compiling A.java using javac -verbose -g pkgA.java. Notice that the compiler is looking in the current directory for .java files :

[解析开始pkgA.java][解析完成29ms][源文件的搜索路径:[.]]

要确认 sourcepath 设置为 CLASSPATH,您可以尝试使用 -cpCLASSPATH> 使用 javac -cp C: -verbose -g pkgA.java 编译 A.java 选项.A.java 这次将不会编译,因为您已将 CLASSPATH 覆盖为 C: 而这就是 sourcepath也将默认为.这是输出:

To confirm that the sourcepath is set to CLASSPATH, you can try changing the CLASSPATH using the -cp option by compiling A.java using javac -cp C: -verbose -g pkgA.java. A.java will not compile this time since you have overwritten the CLASSPATH to C: and that's what sourcepath will default to as well. This is the output :

[解析开始pkgA.java]【解析完成26ms】[源文件的搜索路径:[C:]]pkgA.java:3:找不到符号符号:B类

另外,如果当前目录是/top/wrk/pkg 那么命令 javacA.java 有效.怎么样?

Also if the current directory is /top/wrk/pkg then the command javac A.java works. How so?

无论 B.class 是否存在于 pkg

免责声明:我只能在 Windows 上确认这种行为,但我非常怀疑它在其他操作系统上应该有什么不同.

Disclaimer : I can only confirm this behavior on Windows but I highly doubt that it should be any different on other operating systems.

相关文章