How can I prevent Eclipse from importing nested classes?
Whenever I use nested classes, I give them names not including the outer class name, e.g.,
MySomething.Kind
and not MySomething.MySomethingKind
. The nested classes are sometimes visible to the outside and then I want to refer to them always by the name qualified by the enclosing class, i.e., MySomething.Kind
and not just Kind
. Sometimes there are multiple classes containing a nested Kind
, so using the unqualified name may be confusing.
Is there any way to prevent Eclipse from needlessly importing mypackage.MySomething.Kind
instead of using (already imported) mypackage.MySomething
together with the semi-qualified name?
UPDATE:
This doesn't happen spontaneously. As stated by jprete, when I always use the semi-qualified name, the nested class doesn't get imported. But any refactoring creating a variable of type MySomething.Kind
declares it as Kin开发者_如何学运维d
only and adds the unwanted import statement. This turns the refactoring to useless, as I have to edit it manually. Whenever I forget, I get the worst of both: a mixture of unqualified and semi-qualified names.
I have found that, if I always refer to the nested class with the "semi-qualified" name - i.e. MySomething.Kind
rather than Kind
- that Eclipse will not try to automatically add import mypackage.MySomething.Kind
when I tell it to reorganize imports, but instead will only add import mypackage.MySomething
and leave the "Class.NestedClass" references alone.
It looks like there's no solution, but what I'm doing now is pretty practical (when used in a script):
find src -name "*.java" | xargs perl -pi -e \
's/^(import [.\w]+\.)([A-Z]\w+)(\..*);/$1$2;/;'
It simply replaces all the unwanted imports like
import java.util.Map.Entry;
by the outer class imports like
import java.util.Map;
It's matter of seconds to fix the errors manually and let organize imports get rid of duplicates. It ignores static imports as I want.
Warnings:
- it touches all files (solution)
- you have to refresh them in eclipse
- it modifies the source code, which is something nobody should do without a source control
精彩评论