Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fully qualify a class whose package name collides with a local member name?

OK, here's a very curious Java 7 language puzzle for the JLS specialists out there. The following piece of code won't compile, neither with javac nor with Eclipse:

package com.example;

public class X {
    public static X com = new X();

    public void x() {
        System.out.println(com.example.X.com);
        // cannot find symbol  ^^^^^^^
    }
}

It appears as though the member com completely prevents access to the com.* packages from within X. This isn't thoroughly applied, however. The following works, for instance:

public void x() {
    System.out.println(com.example.X.class);
}

My question(s):

  • How is this behaviour justified from the JLS?
  • How can I work around this issue

Note, this is just a simplification for a real problem in generated code, where full qualification of com.example.X is needed and the com member cannot be renamed.

Update: I think it may actually be a similar problem like this one: Why can't I "static import" an "equals" method in Java?

like image 258
Lukas Eder Avatar asked Oct 16 '13 14:10

Lukas Eder


People also ask

Can we have two classes with same name under the same package?

Yes there is. You would need to implement your own Classloader and play some games to be able to access both during runtime.

Can we give fully qualified class name instead of importing that class if yes how do you do that?

3) Using fully qualified name Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface. It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.

Can we have multiple Java classes with the same name in the same package?

A Java file contains only one public class with a particular name. If you create another class with same name it will be a duplicate class. Still if you try to create such class then the compiler will generate a compile time error.

Can two packages have same name in Java?

Yes, you can have two classes with the same name in multiple packages.


1 Answers

This is called obscuring (jls-6.4.2).

A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type, or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. Thus, it is may sometimes be impossible to refer to a visible type or package declaration via its simple name. We say that such a declaration is obscured.

like image 79
Sotirios Delimanolis Avatar answered Nov 23 '22 23:11

Sotirios Delimanolis