Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic imports in Eclipse

Tags:

java

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?

like image 615
Martin Avatar asked Dec 01 '25 02:12

Martin


2 Answers

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.

like image 96
cello Avatar answered Dec 02 '25 16:12

cello


So I noticed that Eclipse had started to seemingly do all the necessary imports completely automatically. And I started to look for how Eclipse can automatically add imports.

But all I could find was to use the Ctrl+Shift+O shortcut to Organize imports. And that could probably be quite efficient if you want to do many at a time.

However there are at least two (or maybe three) other methods to invoke this.

  1. Window, preferences, Java, Editor, Save actions. You will need to check: "Perform the selected actions on save" and "Organize imports".
  2. Window, preferences, Java, Editor, Typing: Under "When pasting" you can select "Update imports".
  3. I am not sure if this is a way of it's own or if it is a variant of what happens when pasting. But if you use ctrl + space to help with auto completing what you are writing it will also Organize imports. So for example if I have no imports in a class and I start typing: JP and then I press ctrl + space to help me complete and I choose JPanel it will apparently automatically add: import javax.swing.JPanel; for me.
like image 20
Oscar Josefsson Avatar answered Dec 02 '25 16:12

Oscar Josefsson