Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eclipse Optimize Imports to Include Static Imports

Is there anyway to get Eclipse to automatically look for static imports? For example, now that I've finally upgraded to Junit 4, I'd like to be able to write:

assertEquals(expectedValue, actualValue); 

hit Ctrl + Shift + O and have Eclipse add:

import static org.junit.Assert.assertEquals; 

Maybe I'm asking too much.

like image 455
Paul Croarkin Avatar asked Nov 14 '08 00:11

Paul Croarkin


People also ask

How do I add a static import?

In Eclipse IDE, you can select the whole reference variable and press Ctrl+Shift+M and it will automatically import that static element using static import in Java.

How do I enable import suggestions in Eclipse?

Try this: Go to Preferences » Java » Editor » Content Assist » Advanced. Make sure Other Java Proposals is ticked/checked. If that does not work simply close the project and reopen it.

How do I fix all imports in Eclipse?

Press: CTRL + SHIFT + O and you should see below dialog boxes. Choose your desired import package and click next. It will prompt you for your next import and thats it. You are done.

How do I manage imports in Eclipse?

To enable this, go to Windows -> Preferences -> Java -> Editor -> Save Actions and then enable Perform the selected action on save -> Organize imports. After this, whenever you save a java file, eclipse will remove the unused imports automatically.


2 Answers

I'm using Eclipse Europa, which also has the Favorite preference section:

Window > Preferences > Java > Editor > Content Assist > Favorites

In mine, I have the following entries (when adding, use "New Type" and omit the .*):

org.hamcrest.Matchers.* org.hamcrest.CoreMatchers.* org.junit.* org.junit.Assert.* org.junit.Assume.* org.junit.matchers.JUnitMatchers.* 

All but the third of those are static imports. By having those as favorites, if I type "assertT" and hit Ctrl+Space, Eclipse offers up assertThat as a suggestion, and if I pick it, it will add the proper static import to the file.

like image 180
Joey Gibson Avatar answered Sep 27 '22 00:09

Joey Gibson


If you highlight the method Assert.assertEquals(val1, val2) and hit Ctrl + Shift + M (Add Import), it will add it as a static import, at least in Eclipse 3.4.

like image 30
Dave L. Avatar answered Sep 26 '22 00:09

Dave L.