在线解决挑战时,我发现了
java的以下行为,我发现它有点奇怪.我从以下大纲编写程序开始:
import java.io.*; class WeirdJava { public static void main (String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine(); HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); System.out.println("Weird Java"); } }
请注意,在上面的程序中,有两个错误:
>我没有处理BufferedReader可能抛出的异常.
>我没有导入包含HashMap的标准util库.
现在,当我尝试编译上面的程序时,java编译器给出了它无法找到符号HashMap的错误.请注意,涉及HashMap的声明位于BufferedReader之后.接下来,我将以下import语句添加到程序中:
import java.util.HashMap;
unreported exception IOException; must be caught or declared to be
thrown
我的问题:
解决方法
它只是编译器检查源的顺序.特别是,在检查调用可以引发已检查异常的方法的代码之前,编译器会检查导入并解析它们.
如果你用-verbose运行javac,你会注意到编译器加载了导入的类,在本例中是BufferedReader和InputStreamReader,然后它加载了像Object和String这样的公共API类:
[loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/BufferedReader.class)]] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/InputStreamReader.class)] ] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/Object.class)]] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/String.class)]] [checking test.Test] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/AutoCloseable.class)]] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/lang/System.class)]] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/InputStream.class)]] [loading ZipFileIndexFileObject[C:\Dev\Java\jdk1.7.0_75\lib\ct.sym(Meta-INF/sym/rt.jar/java/io/Reader.class)]] Test.java:11: error: cannot find symbol HashMap<Integer,Integer>();
通过查看this link中的概述,加载已使用的类本身是第一阶段编译的一部分,称为“Parse and Enter”:
Each tree is passed to Enter,which enters symbols for all the definitions encountered into the symbols. This has to done before analysis of trees which might reference those symbols. The output from this phase is a To Do list,containing trees that need to be analyzed and have class files generated.