Working With Static Imports in Eclipse

Eclipse has few features that make working with static imports almost as easy as it should be.

Add Import Keyboard Shortcut

Many people I work with were surprised that the “add import” shortcut works also for static imports. Just set the cursor on the static method, static field or enum constant, press Ctrl+Shift+M and it will be imported statically. I think it should also be available as a quick fix. This way more people would notice it.

Favorites

For most often used static imports it’s more convenient to add them as favorites. In order to do that go to Preferences -> Java -> Editor -> Content Assist -> Favorites. You can add static members and whole classes there.

Eclipse favorites menu

Once you add a static member or its class to the favorites it becomes available in code completion.

assertEquals with code completion in Eclipse

Imports Organization

You can control how static imports are organized when using the options above. There can be either a separate import for each static member or a wildcard character to import all members from a given type. It can be set in Preferences -> Java -> Code Style -> Organize Imports. By default the number of static imports needed for using the wildcard character is 99. If you set it to 1 Eclipse will always use the wildcard when adding static imports.

Additional Comments

If the code completion adds normal instead of static imports for favorites check whether “use static imports” option is set in Preferences -> Java -> Editor -> Content Assist.

Share
This entry was posted in Java and tagged , , , . Bookmark the permalink.

3 Responses to Working With Static Imports in Eclipse

  1. Jero says:

    Nice post. Thanks for sharing.

  2. Dayo says:

    Tanx. wasnt aware of dis.

  3. The Alchemist says:

    Great tip!

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>