Avoid repeated imports in Java: Inherit imports?

2019-04-04 17:45发布

问题:

Is there a way to "inherit" imports?

Example:

Common enum:

public enum Constant{ ONE, TWO, THREE }

Base class using this enum:

public class Base {
    protected void register(Constant c, String t) {
      ...
    }
}

Sub class needing an import to use the enum constants convenient (without enum name):

import static Constant.*; // want to avoid this line!  
public Sub extends Base {
    public Sub() {
        register(TWO, "blabla"); // without import: Constant.TWO
    }
}

and another class with same import ...

import static Constant.*; // want to avoid this line!
public AnotherSub extends Base {
    ...
}

I could use classic static final constants but maybe there is a way to use a common enum with the same convenience.

回答1:

imports are just an aid to the compiler to find classes. They are active for a single source file and have no relation whatsoever to Java's OOP mechanisms.

So, no, you cannot “inherit” imports



回答2:

No, you can't inherit an import. If you want to reference a type within a class file without using the fully-qualified name, you have to import it explicitly.

But in your example it would be easy enough to say

public Sub extends Base {
    public Sub() {
        register(Constant.TWO, "blabla"); // without import: Constant.TWO
    }
}


回答3:

If you're using Eclipse, use "Organize Imports" (Ctrl+Shift+O) to let the IDE do the imports for you (or use code completion (Ctrl+Space)