Java解析点分标识符
Java 使用什么规则来解析点分标识符?
例如:
import Foo.Bar;
class Foo
{
public static class Bar
{
};
};
现在,Foo.Bar
可以引用导入的类Bar
或源代码中定义的类。这种模糊性是如何解决的呢?
我已经尝试过这个案例,所以我知道实践中会发生什么,但我正在寻找更多;我想知道基本规则。例如,如果源文件中存在Foo.Bar
,我是否还可以引用导入的类Foo.Bar.Baz
?如果 Foo.Bar
既是一个包又是一个类怎么办?如果编译器在最近的 Foo
中找不到 Foo.Bar
,它会放弃,还是继续寻找其他 Foo
s 直到它用完或找到一个匹配的?
(顺便说一句,我已经在语言规范中找到了相关位。它没有多大帮助......)
What are the rules Java uses to resolve dotted identifiers?
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. 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
? What if Foo.Bar
is a package and also a 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?
(Incidentally, I have found the relevant bit in the language specification. It doesn't help much...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了解决这样的奇怪冲突,java 编译器遵循与解决局部变量名称与实例字段名称冲突等问题相同的规则 - 它使用“最近的”声明。在这种情况下,本地类 Foo 将胜过导入类。
当导入两个同名的类时,也可能会发生冲突。最常见的示例是 java.util.Date 和 java.sql.Date。如果您已将它们都导入到您的类中,则必须使用它们的完全限定名称来引用它们。
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. In this case, the local class Foo will win over the imported one.
A clash can also happen when two classes of the same name is being imported. The most common example is
java.util.Date
andjava.sql.Date
. If you have imported them both into your class, you must refer to them using their fully qualified name.