39
votes

I use the Eclipse keyboard shortcut Ctrl + Shift + O all the time (Organize Imports).

However, it has one particularly annoying behavior:

If I have any static imports like:

import static java.lang.Math.*;

Organize Imports will "helpfully" replace it with static imports of only the fields and methods I am actually using. For example:

import static java.lang.Math.PI;
import static java.lang.Math.cos;

Is there any way to remove just this behavior from Organize Imports?

1
I'm aware that using static import * will pollute my class' namespace with potentially lots of unused bindings and that static imports can make code less readable. Nevertheless I'd like to figure out how to do this in Eclipse.ulmangt
I normally just type e.g. "Math.PI" and then Ctrl-Alt-M, which creates the static import. You only have to do this once pr static import.Thorbjørn Ravn Andersen
Why does this matter? I presume you're asking about "fields and methods I am actually using at the moment", and that you want to be able to use sin without typing Math, Ctrl + Shift + O, Ctrl + S, .sin, Ctrl + Space, left, left, Ctrl + Alt + MStephen
Interesting, I wasn't aware of Ctrl-Alt-M. Not exactly what I'm after, but it does get close.ulmangt
@Stephen I's just a convenience thing. I have a class with a number of static fields, all of which I might need. I'd like to simply add the static import * for that class and forget about it, allowing me to simply use the fields by their name (no messing around with keyboard shortcuts). However, I do occasionally use ctrl+shift+o to clean up unused imports, etc... and when I do that it removes my static import *.ulmangt

1 Answers

52
votes

Sure: Window -> Preferences -> Java -> Code Style -> Organize Imports

Adjust the value for "Number of static imports needed for .*" to 1, and it will always use .*. Of course, that's not quite the same as saying, "Just leave static imports alone" but hopefully it's what you want.

Basically, this number says "Use all of the methods or fields of this import if I'm importing this many items" So if the number is 2, it will add the asterisk only if you use two or more imports. That will fix the problem you said in the response.