ddavison
ddavison

Reputation: 29032

Eclipse optimize imports to include static members and methods

Long user of eclipse and Java. One issue that i've found with Eclipse, is it seems that there is no easy way to import static members and methods.

Namely, the jUnit fail() method from org.junit.Assert

I create several classes a day, and manually add

import static org.junit.Assert.fail;

to the import statements. This is quite annoying. I absolute LOVE using Ctrl+Shift+O to organize my imports, but it still doesn't find static members and methods.

Also, the import does not show up in eclipse.
enter image description here

Funny thing is, is that i've seen it work previously, but i cant recall the variables.

So to my question:

Does anybody know what I need to do to ensure that this static import is always recognized and can be found using Ctrl+Shift+O?


Thanks @qqilihq.

Note:

The answer that was accepted does not work with the Organize Imports keyboard shortcut that I preferred in eclipse, but does work for the "hover over" suggestion.

Upvotes: 28

Views: 12511

Answers (3)

qqilihq
qqilihq

Reputation: 11454

Did you have a look at Preferences > Java > Editor > Content Assist > Favorites? You can define candidates for static imports there. Result:

enter image description here

For less used classes you can lower the value of Preferences > Java > Code Style > Organize Imports > Number of static imports needed for .* but beware that you may get .* for classes that contain generically named methods such as getInstance. This in turn may lead to confusion and/or naming conflicts.

Upvotes: 28

Sachin Gorade
Sachin Gorade

Reputation: 1467

You can use Ctrl + Shift + M, for example you want to import verify method from Mockito class then

Mockito.verify() // select verify and press Ctrl + Shift + M

This will import verify static method from Mockito class.

Upvotes: 34

ovunccetin
ovunccetin

Reputation: 8663

You can add the classes that you statically import from Preferences > Java > Editor > Content Assist > Favorites page in Eclipse. Then, Ctrl+Space shortcut lists all the static members of your favourite classes in the content assist menu.

Upvotes: 2

Related Questions