javaeclipse

Automatic imports in Eclipse


In Eclipse, I have to press Ctrl+Space each time I refer to the type of an unimported class. Having to go back and press Ctrl+Space feels rather unnecessary. Is there a way to make Eclipse behave like IntelliJ in this case? It should not really be hard to know it should import the UserFactory and User class when I say:

User user = UserFactory.makeUser();

I've seen that you can press Ctrl+1 (quick fix) or Ctrl+Shift+O (Organize imports) to solve this problem, but I would like this to go automatically as it does in IntelliJ.

Does anyone know a plugin or a setting that enables this type of behavior?


Solution

  • Open Eclipse's preferences and then go to "Java > Editor > Save Actions". There, enable "Organize Imports".

    Now, whenever you save your file (yes, in Eclipse you still need to save the file, not as in IntelliJ where this happens automatically), Eclipse will try to figure out if it needs to add imports to compile the code. It will do so whenever the class name is unique. If it is not (e.g. List in java.util and in java.awt), it will not import it.

    You can configure the "organise imports" action even more to ignore certain packages (e.g. java.awt if you never to gui-stuff), so you have fewer name-conflicts and more auto-imports. Look at question Exclude packages from Eclipse's organize imports for infos how to do that.