Friday, July 11, 2008

Eclipse Tip: Static Imports

One of the great features of Java 1.5 is Static Imports. In order to configure Eclipse to search for static imports in a particular class, you have to perform the following steps:

  1. Navigate to Preferences by clicking on the Window -> Preferences Menu Item
  2. Navigate to Java -> Editor -> Content Assist -> Favorites using the menu tree (or search for Favorites using the search bar at the top)
  3. Click the New Type button
  4. Type in the name of the Class that has static methods that you would like to be used when using Eclipse's Content Assist / Code Completion (eg Assert)
  5. Click on the Browse button which will bring up the Open Type Dialog using what you entered previously as the search criteria
  6. Find the class that you would like to add, and then click Okay on the Open Type Dialog
  7. Then Click Okay on the New Type Favorite Dialog.
Now when you are editing Java code, instead of typing Assert.assertEquals, you only need to type assertEquals, with Ctrl-Space, and the Assert Type will be searched for in order to resolve the static import.

If this helps, pay it forward....


Jeremy D. Frens said...

Hey, Carlus! I stumbled on this Eclipse feature a while ago but had forgotten about it. Thanks for reminding me.

One question: setting this content assist helps with ctrl-space completion, but it apparently doesn't help with Source -> Organize Imports. I know, who would do things this way? But sometimes it would be useful. Do you know if there's a separate setting for Organize Imports? Can you tell me if you do (smile)?

Carlus Henry said...

Funny you should mention this. I just stumbled across a post that tells exactly how to do just what you are looking for.

Organizing Static Imports

Jeremy D. Frens said...

Actually, that only works if there's a static import already there. Then Eclipse will use the .* form to statically import everything from the specified class.

Unfortunately, it won't add new static imports.

I figured out when this is a problem for me: when I introduce a static-method call with a template (like "ear" for an EasyMock "expect().andReturn()".)

Inventory Management Software said...

Thanks for sharing your post and it was superb .I would like to hear more from you in future too.

Anonymous said...

Great tip!! Thank you.

Blundell said...

Loving it, just used this my new Mockito unit tests! Thanks