Java parsing of dotted identifiers
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 im开发者_开发技巧ported 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...)
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
and java.sql.Date
. If you have imported them both into your class, you must refer to them using their fully qualified name.
精彩评论