How do you import static in Eclipse?

Home  >>  Eclipse  >>  How do you import static in Eclipse?

How do you import static in Eclipse?

On March 28, 2012, Posted by , In Eclipse, By , With 5 Comments

Long story short, I just discovered that Ctrl+Shift+M (Source > Add Import) can not only be used to add missing imports. It can also help with static imports. Executed on a reference to a qualified member (read Class.member), the refactoring will add a static import for the defining class and remove the class-dot expression.

For example, if you have

import java.lang.System;
class Example {
  void someMethod() {
    System.currentTimeMillis();
  }
}

Place the cursor on currentTimeMillis() and press Ctrl+Shift+M. This will transform the code to

import static java.lang.System.currentTimeMillis;
class Example {
  void someMethod() {
    currentTimeMillis();
  }
}

This feature has probably been here for a while and is documented and was announced in a New & Noteworthy. I only just discovered it the other day and found that it highly improves working with static imports. Maybe you find it useful too…

The long part of the story…

Tired of often manually managing static imports and encouraged by the new API for quick assists in JDT, I started writing a quick assist. This quick assist should replace qualified calls to static methods with static imports.
Only after I already had a mostly working implementation, I searched the JDT bugzilla for such an enhancement request to eventually provide a patch. Thereby I discovered that Ctrl+Shift+M already does the job.
In the end, I spent an evening coding and got to know new APIs of JDT, learned a new feature of an old shortcut and was remembered to “think first, then act”. :)

Rüdiger Herrmann

Rüdiger started writing software more than 20 years ago. From the very beginning he focused on a pragmatic approach to writing and delivering software.

His interests include promoting test driven development and agile methods to deliver clean code that works.

(EMail: rherrmann@codeaffine.com)

5 Comments so far:

  1. Felix says:

    Thanks!

  2. Matthieu Brouillard says:

    Cool hint!

    Another way also of dealing with frequent static import is by defining “available” static imports for content assist.
    You can do this in > Preferences > Java > Editor > Content Assist > Favorites.
    In my preferences I always have : org.junit.Assert.* and org.hamcrest.CoreMatchers.*.
    Then writing test, I can type: assertTh + CTRL-SPACE, and then eclipse will propose me directly the assertThat method and import static it.

  3. Mike says:

    Great stuff! Adding each class to favourites is a pain in the backside.

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>