[英]Java parsing of dotted identifiers
What are the rules Java uses to resolve dotted identifiers? Java 用于解析点标识符的规则是什么?
For example:例如:
import Foo.Bar;
class Foo
{
public static class Bar
{
};
};
Now, Foo.Bar
can refer to either the imported class Bar
or the one defined in the source code.现在,
Foo.Bar
可以引用导入的 class Bar
或源代码中定义的 Bar。 How is this kind of ambiguity resolved?这种模棱两可的问题是如何解决的?
I have tried this one case so I know what happens in practice, but I'm looking for more than that;我已经尝试过这个案例,所以我知道在实践中会发生什么,但我正在寻找更多; I want to know the underlying rules.
我想知道基本规则。 For example, if
Foo.Bar
exists in the source file, can I still refer to the imported class Foo.Bar.Baz
?例如,如果
Foo.Bar
在源文件中存在,我是否仍然可以引用导入的 class Foo.Bar.Baz
? What if Foo.Bar
is a package and also a class?如果
Foo.Bar
是 package 和 class 怎么办? If the compiler can't find Foo.Bar
in the closest Foo
, does it just give up, or does it keep looking for other Foo
s until it either runs out or finds one that matches?如果编译器在最近的
Foo
中找不到Foo.Bar
,它会放弃,还是继续寻找其他Foo
直到它用完或找到匹配的?
(Incidentally, I have found the relevant bit in the language specification. It doesn't help much...) (顺便说一句,我在语言规范中找到了相关位。它没有多大帮助......)
To resolve a weird clash like this, the java compiler follows the same rules it uses to resolve things like local variable names clashing with instance field names - it uses the "nearest" declaration.为了解决这样的奇怪冲突,java 编译器遵循它用来解决局部变量名称与实例字段名称冲突等问题的相同规则——它使用“最近”声明。 In this case, the local class Foo will win over the imported one.
在这种情况下,本地 class Foo 将胜过进口的。
A clash can also happen when two classes of the same name is being imported.当导入两个同名的类时,也会发生冲突。 The most common example is
java.util.Date
and java.sql.Date
.最常见的例子是
java.util.Date
和java.sql.Date
。 If you have imported them both into your class, you must refer to them using their fully qualified name.如果您已将它们都导入到 class 中,则必须使用它们的完全限定名称来引用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.