Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import static without package name

Consider the following simple example of code:

public class TestStaticImport {
    static enum Branches {
        APPLE,
        IBM
    }
    public static void doSomething(Branches branch) {
        if (branch == APPLE) {
            System.out.println("Apple");
        }
    }
}

If we will try to compile this code, we will get the error message:

java: cannot find symbol
  symbol:   variable APPLE
  location: class TestStaticImport

This could be solved by introducing static import of this enum:

import static ... TestStaticImport.Branches.*

But in this moment incomprehensible things (for me) begin:

this solution works fine, everything is well compiled, until class TestStaticImport will be moved into empty root package, i.e. there isn't any

package blablabla; in the top of this java file;

Code line: import static TestStaticImport.Branches.*; is highlighted as valid code in my Intellij IDEA (name of IDE doesn't matter, just for information), but when I try to compile such code following error appears:

java: package TestStaticImport does not exist

So, there are actually two questions:

1) Main question: why is it impossible to import static from empty directory?

2) What is another way (if it exists) for allowing in code references to enum's fields using just their names (i.e. APPLE instead of Branches.APPLE), except static import?


P.S. Please, don't tell me, that empty packages is ugly style and so on. This question is just theoretical problem.

like image 811
Andremoniy Avatar asked Jan 10 '13 12:01

Andremoniy


1 Answers

The Java language specification forbids any imports from the unnamed package:

A type in an unnamed package (§7.4.2) has no canonical name, so the requirement for a canonical name in every kind of import declaration implies that (a) types in an unnamed package cannot be imported, and (b) static members of types in an unnamed package cannot be imported. As such, §7.5.1, §7.5.2, §7.5.3, and §7.5.4 all require a compile-time error on any attempt to import a type (or static member thereof) in an unnamed package.

like image 143
McDowell Avatar answered Sep 20 '22 19:09

McDowell