java自动编译,javac如何自动编译类的依赖关系

Given the following directory structure:

/top

|--- wrk

|--- pkg

|--- A.java

|--- B.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 {...}

Assuming that the current directory is /top/wrk

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

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

解决方案

Why does the command javac -cp . pkg/A.java work successfully even though we have not yet compiled B.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.

From the Oracle documentation for javac :

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

From the Oracle document for CLASSPATH

The default value of the class path is "."

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 pkg\A.java. Notice that the compiler is looking in the current directory for .java files :

[parsing started pkg\A.java]

[parsing completed 29ms]

[search path for source files: [.]]

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 pkg\A.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 :

[parsing started pkg\A.java]

[parsing completed 26ms]

[search path for source files: [C:\]]

pkg\A.java:3: cannot find symbol

symbol : class B

Also if the current directory is /top/wrk/pkg then the command javac

A.java works. How so?

This will not work regardless of whether B.class is present in pkg

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值