If I have a constant BAR in Foo, which I will use in a class C I'll have to write
Object o = Foo.BAR + "...";
which I can use Ctrl-Shift-M in Eclipse (with the cursor on BAR) to create a static import for like:
import static Foo.BAR; Object o = BAR + "....";
I am current updating legacy code with literaly thousands of these I'd like to convert to static imports. Ctrl-Shift-O / Organize imports does not do it. Is there a trick I've missed?
EDIT: Actually, what I would prefer is a way to tell Eclipse that I want to have Ctrl-Shift-M do its magic on ALL instances in this particular class instead of just the single instance I have the cursor placed at. (It is legacy code so this actually IMPROVES readability :) )
EDIT: I've found that IntelliJ suggest doing this.
In Java, static import concept is introduced in 1.5 version. With the help of static import, we can access the static members of a class directly without class name or any object. For Example: we always use sqrt() method of Math class by using Math class i.e. Math.
Static import is a feature introduced in the Java programming language that allows members (fields and methods) which have been scoped within their container class as public static , to be used in Java code without specifying the class in which the field has been defined.
If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from.
Static import in Java allows importing static members of the class and use them, as they are declared in the same class. Static import is introduced in Java 5 along with other features like Generics, Enum, Autoboxing and Unboxing and variable argument methods.
One cautionary note: excessive use of static imports can actually make your code less readable (imho), particularly if the constant name doesn't clearly indicate the class or enum from which it belongs. You can also get constant names from different classes/enums that sound similar or even have the same name.
So what you're forcing the reader to do is hope his IDE will tell him the class (via, say, a tool tip) or they have to navigate to it to find out what it is. Printouts and code snippets become that much less reeadable.
Honestly I use static imports extremely rarely for these reasons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With