Static Import Code Completion

As much as I love Java 5 static imports, I’m finding code completion to be more than a little bit frustrating. This is most annoying when I start writing new code with frameworks that make heavy use of static imports, like JUnit 4.4.

The cycle goes something like this:

  1. Create a new source file
  2. Type Assert., then the IDE recognizes I’m missing an import.
  3. Alt-Enter to add the import statement. NOTE: Hopefully I remember to choose org.junit.Assert instead of junit.framework.Assert. Even as I write this, I’m wondering if I just got that backwards? Confusing as hell.
  4. Now I can use code completion (Ctrl-space) to fill in the assertThat(...) method.
  5. Now hit Alt-Enter to add the static import for Assert.assertThat
  6. Now hit YET ANOTHER keystroke to optimize imports, because the old import org.junit.Assert; is no longer used.

Once you go through this “priming the pump” sequence, code completion with static imports works better. But reaching that point makes my hand hurt and is a new awkward wrinkle to Java programming.

Perhaps other IDEs work better than IDEA at static import code completion? (I’d be very surprised, but who knows…)

What do you think? Surely I’m not the only person to stumble on this.


Sam.Halliday Says:

I found a little Eclipse feature a few weeks ago that may be the cure for all your woes…

Java -> Editor -> Content Assist -> Favorites [sic]

and there you can add all your favourite static utility classes and you don’t have to manually import them. If you find yourself importing the wrong classes all the time, consider adding the bad ones (i.e. com.*, sun.*, sunw.*) to

Java -> Appearance -> Type Filters

Peter Lawrey Says:

IDEA also auto fixes
assertEquals(true, x) => assertTrue(x)
assertEquals(false, x) => assertFalse(x)
assertTrue(a == b) => assertSame(a,b)
assertTrue(a.equals(b)) => assertEquals(a,b)
assertEquals(null, x) => assertNull(x)

The more interesting one is
assertEquals(expression, constant) eg assertEquals(x – x, 0) => assertEquals(constant, expression)
i.e. the first argument should be the expected value