Essential tools to manage import statements in Eclipse

It’s a big hassle to manually organise package import statements so it’s important to know what tools are available so your IDE can handle imports as quickly and quietly as possible.

Adding import statements for missing references and removing unused imports can take ages and the list of imports can get very long and hard to manage. As an example, the import statements below can consist of static/normal imports and wildcard/class imports:

// The list of imports can get really long...
import static org.junit.Assert.assertEquals; // Static imports
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.lang.*; // Wildcard; unused so should be removed
...
public class MyTest {
   @Test
   public void testSomething() throws Exception {
      List<String> messages = new ArrayList<String>();
      assertEquals(1, 1);
   }
}

To make life easier, Eclipse has a heap of features that automatically manage import statements, including organising them when you save or when you press a keyboard shortcut. It can even deal with static imports. This tip covers some of these features, starting with the absolute essentials that save loads of time and moving on to more optional features that will depend on your environment and tastes.

Steps to managing import statements

Here’s a brief overview of the features I’ll cover and the order in which I would recommend them for maximum productivity, going from essential to nice-to-know. Pick and choose to your liking:

  1. Let Eclipse automatically organise imports whenever you save a file. (Essential)
  2. Learn keyboard shortcuts for when format-on-save doesn’t work or if you prefer to not enable it. (Essential)
  3. Configure static imports so that Eclipse suggests them on autocomplete or quick fix. (Essential)
  4. Let Eclipse collapse imports in the same package a wildcard (.*) or expand them individually. (Good to know)
  5. Add type filters for unwanted packages, eg. exclude java.awt.List from autocomplete. (Good to know)
  6. Look at some other features like folding and package compression/abbreviation. (Nice-to-have)

1. Automatically organise import statements whenever you save

Eclipse can automatically format code every time you save. However, it can also add missing imports and remove unused imports when you save so you don’t have to worry about remembering to tell Eclipse to organise it.

Here are the steps to organising imports whenever you save:

  1. Go to Window > Preferences > Java > Editor > Save Actions.
  2. Select Perform the selected actions on save (off by default).
  3. Ensure that Organize imports is selected (on by default).

Note: You don’t have to enable automatic code formatting to automatically organise imports. See this post for more information on the other settings in the dialog, specifically the Format source code option.

2. Learn the keyboard shortcuts for organising imports

If you prefer not to organise imports when you save, then you can organise them on-demand by using keyboard shortcuts. However, unlike organise-when-you-save, you’ll have to remember to press the shortcut every time you may have changed the import list.

Shortcut Command Description
Ctrl+Shift+O Organise Imports Adds missing imports and removes unused imports. In the case of name conflicts (ie. the same class name in different packages), a dialog pops up prompting you for the class you intended to use.
Ctrl+Space Content Assist (Autocomplete) As you type a class name, press Ctrl+Space to bring up Eclipse’s autocomplete. Once you press Enter to select it, Eclipse will automatically add an import for the class.
Ctrl+1 Add Import (Quick Fix) This Quick Fix adds a missing import for a referenced class with a compile error (can only be used if there’s a compile error). You really shouldn’t need to use this that often if you use the other keys.

I recommend using autocomplete most of the time and using Ctrl+Shift+O in cases where, for example, you pasted code from somewhere else or the rare occasion the automatic import organisation doesn’t work, eg. it copes better with severe compiler errors.

3. Configure static imports so Eclipse suggests them on autocomplete

Static imports are required if you want to use static methods without qualifying them with their class name, eg. JUnit’s assertEquals().

I’ve already covered how to generate static imports when you use autocomplete, so please refer to that post for details.  In summary, you’ll have to enable static imports on autocomplete (possibly on by default in Eclipse 4.x) and then add the classes you want autocompleted to Eclipse’s Favorites.

 4. Let Eclipse collapse imports in the same package a wildcard (.*) or always expand them

There isn’t really consensus on whether you should use wildcards on package imports (eg. org.eclipse.swt.*) or whether to specify them individually (eg. org.eclipse.swt.SWT).

By default, Eclipse imports classes individually but you can tell it to always convert them into wildcards:

  1. Go to Window > Preferences > Java > Code Style > Organize Imports.
  2. Change the value of Number of imports need for .* to 0.
  3. (Optional) Change the value of Number of static imports needed for .* to 0.

5. Exclude unwanted packages using Type Filters

You can use Type Filters to prevent some classes from getting in the way when you use autocomplete or Ctrl+Shift+O (organise imports dialog). For example, autocompleting for List suggests java.util.List and java.awt.List. ~100% of the times you want java.util.List so here’s how to do that.

  1. Go to Window > Preferences > Java > Appearance > Type Filters.
  2. Click Add… to add a package/class.
  3. Enter java.awt.List (or java.awt.* if you don’t intend using any AWT classes).

Note: These classes also won’t appear in some other places such as the Open Type dialog so don’t be surprised when you don’t see them.

6. Look through some these other features

The following aren’t as time-saving as the features above but may be useful for your tastes/environment:

  • Folding: By default, Eclipse folds all import statements into one line so your class takes up less space on the screen. You can change this by going to Window > Preferences > Java > Editor > Folding and deselecting Imports.
  • Sorting: If you’re really particular about the order of packages, you can go to Window > Preferences > Java > Code Style > Organize Imports and define the order of the packages as you want Eclipse to order them. It’s not really worth the effort though so I’d skip it.
  • Compress/abbreviate package names in the Package Explorer (not in your class but in the view): You can display packages compressed (eg. o~.e~.swt) or abbreviated (eg. org.eclipse.swt.custom becomes {SWT}.custom). Go to Window > Preferences > Java > Appearance and define the settings there. The dialog has decent examples of how to do this.

Related tips

Support Eclipse On E

5 thoughts on “Essential tools to manage import statements in Eclipse

  1. Good summary!

    I wouldn’t recommend organize-imports-on-save though. During Debug-time it should be ok to have unorganized imports, e.g. unnessecary ones. Then you can temporarily take pieces of code out, without their imports getting lost. Strg+Shift+O doesn’t always find unique imports (and doesn’t have to!), so there would always be manual work involved.

    My approach is rather: have more than less imports in one file during debugging, and have stable code free of warnings. This involves removing unused imports.

    • Thanks for the comment, Janos. I’ve never really had a problem with organise-on-save. Between it, autocomplete and Ctrl+Shift+O, I’ve never really had to maintain more imports than were necessary.

      If any imports are missing, all 3 would add them. As you rightly mention, organise-on-save doesn’t handle ambiguous imports, but Type Filters do help after a while, esp. for AWT and CORBA classes.

      If imports are removed that I’ll need later, then organise-on-save will just add them back if/when they’re needed, even if it is bulk code that I’ve perhaps commented out for debugging.

      But it’s great that Eclipe supports all these features to allow for different workflows.

  2. ctrl + shift+ o doesnt work for me . I was trying to create a List lst = new ArrayList(); and did control+shift+0 and it just imports java.util.ArrayList and does not import java.util.List . What shoul i do ?

    • I’m not sure why it didn’t import java.util.List. You will often have duplicates for List coming up, specifically java.awt.List and java.util.List. It may be that Eclipse is struggling to show the duplicates when you’ve got errors in your class (which you will if imports aren’t resolved). But normally it should try and resolve List as well. Sorry for not being more help here.

  3. Put your cursor on “List” and press Strg+1 and import manually the right Java.util.List. This is anyway the preferred way, because it safes you from importing wrong stuff (with the same name).
    Anyway, press Strg+1 all the time! 😀

Leave a Reply

Your email address will not be published. Required fields are marked *