How can I prevent Eclipse from importing nested classes?

Whenever I use nested classes, I give them names that do not contain the name of the outer class, for example, MySomething.Kind , and not MySomething.MySomethingKind . Nested classes are sometimes visible from the outside, and then I always want to refer to them by the name assigned to the class, i.e. MySomething.Kind , not just Kind . Sometimes there are several classes that contain a nested Kind , so using an unqualified name can be confusing.

Is there a way to prevent unnecessarily importing Eclipse mypackage.MySomething.Kind instead of using the (already imported) mypackage.MySomething along with a semi- mypackage.MySomething name?

UPDATE:

This does not happen spontaneously. As jprete pointed out , when I always use a semi-qualified name, the nested class is not imported. But any refactoring that creates a variable of type MySomething.Kind declares it only as Kind and adds an unwanted import statement. This makes refactoring useless, since I have to edit it manually. Whenever I forget, I get the worst of both: a mixture of unqualified and semi-qualified names.

+6
source share
2 answers

I found that if I always refer to a nested class with a "semi-qualified" name - that is, MySomething.Kind , and not Kind - that Eclipse will not try to automatically add import mypackage.MySomething.Kind when I talk about this to reorganize the import, but instead, it will only add import mypackage.MySomething and leave only the "Class.NestedClass" links.

+1
source

There seems to be 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]+\.)([AZ]\w+)(\..*);/$1$2;/;' 

It just replaces all unwanted imports, for example

 import java.util.Map.Entry; 

by importing an outer class e.g.

 import java.util.Map; 

It is a matter of seconds to fix the errors manually and allow the import of duplicates to be organized. It ignores static imports as I want.

Warnings:

  • it affects all files ( solution )
  • you need to update them in eclipse
  • it modifies the source code, which no one should do without source control.
0
source

Source: https://habr.com/ru/post/886547/


All Articles