4

For this source code ...

enter image description here

... Eclipse reports the following error:

Only a type can be imported. pkg.a resolves to a package

... while Suns javac compiles it fine.

Similar situation if I try to fully qualify the class pkg.a like this:

enter image description here

Eclipse reports...

pkg.a cannot be resolved to a type

... while Suns javac compiles it fine.


It seems like Eclipse favors interpreting an identifier as a package over a class name, while javac does the exact opposite. So, is it a bug in Eclipse or in javac?

(A reference to the language specification is obviously a plus.)

aioobe
  • 413,195
  • 112
  • 811
  • 826

2 Answers2

3

It is definitely an Eclipse bug:

6.4.2. Obscuring

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.

The clear implication is that it is legal for a class and a package to have the same name. Otherwise, the JLS would say that a class obscuring a package was illegal ... not that the class is used in preference.


Having said that, the only reason you've gotten into this situation is that you've chosen to ignore Java's conventions on naming. Don't expect much sympathy ...

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Do you know if this bug was already reported? In my case I'm depending on a library (JAR) that contains both a class (com.foo.Bar) and some resources in a folder that clash with class name (com/foo/Bar/boo.xml) Here I don't think there is any naming convention violated... Still Eclipse can't compile that. – Julien H. - SonarSource Team Sep 07 '16 at 07:44
1

It's a styling convention to give classes a name starting with a capital letter and packages with a lower case letter; that would solve your problem.

Tom
  • 4,096
  • 2
  • 24
  • 38
  • I did read the question; I consider your problem one of those things that only make life harder if you stand still on them since following a styling convention just avoids it. – Tom Mar 10 '12 at 12:40