Java标识符解析规则

问题描述:

Java编译器在以下类中用于解析Foo的搜索顺序是什么?Java标识符解析规则

class Test 
{ 
    Foo f; 
} 

实证检验显示以下搜索顺序:

  1. 嵌套类
  2. 超类嵌套类
  3. 的java.lang *类
  4. 别人呢?

但我想知道这在Java Language Specification讨论。

我不认为你的意思是有搜索顺序。相反,我认为这条规则适用于:

6.5.5 Meaning of Type Names The meaning of a name classified as a TypeName is determined as follows.

6.5.5.1 Simple Type Names If a type name consists of a single Identifier, then the identifier must occur in the scope of exactly one visible declaration of a type with this name, or a compile-time error occurs. The meaning of the type name is that type.

在此上下文中,导入计为声明;请参阅JLS 6.1。然而,复杂的因素是Shadowing规则(JLS 6.3.1),它说某些类型的声明(在这种情况下是类型)隐藏了现有的声明,而另一些则没有。具体而言,“按需导入”(例如import java.util.*;或隐含导入java.lang.*)不会影响其他声明。

因此,例如;

package foo; 

import java.sql.Date; 
import java.util.*; // import on demand: java.util.Date does not shadow java.sql.Date 
import java.awt.*; // import on demand: java.awt.List does not shadow java.util.List 

class Integer { // (foo.)Integer shadows java.lang.Integer 
    ... 

    static class Integer { // (foo.Integer.)Integer shadows foo.Integer. 
     ... 

     List t = ... // Compilation error, because there are currently two visible 
        // declarations of List (JLS 6.5.5.1) 
    } 
} 

另一皱纹是一个“单型导入”(如上面import java.sql.Date;)阴影在同一封装中声明类型,并导入到需求的类型,但它并不影其他类型的经另一输入“单一类型导入“(JLS 6.3.1)。因此,例如,下面是一个编译错误:

import java.sql.Date; 
import java.util.Date; // Compilation error 
+0

优秀的答案。谢谢! – Gili 2009-12-31 22:38:43

它应该遵循与Scope of Local Variable Declarations中提供的不同范围相同的顺序。

编辑:我的链接所指的执行阶段,而不是编译阶段的JVM规范,由OP Gili

由于它不是一个完整的答案评论,我离开这里的CW启动线。

+0

-1,一旦类已经被编译你的链接“从一个类文件表示派生一个类”是与负载的时间分辨率。我在询问编译器如何解析标识符。您的“局部变量声明的范围”链接指向错误的部分,并且不讨论解析的顺序。 – Gili 2009-12-30 13:55:42