Tuesday, May 1, 2007

Java 5 Feature: Static Imports

Static imports are another convenience feature added to version 1.5 that extends the way imports work in Java. For example, consider the code fragment shown below that calls the static ceil() method on the java.lang.Math class

// x is a number of type double such as 98.765
double y = Math.ceil(x);

With static imports in 1.5, you can ask the Java compiler to import only a class's static portions, as shown, for example, in the rewritten code fragment below:

// Import declaration at the top of the class along with the other imports
import static java.lang.Math.ceil;

// And then somewhere in the code...

// x is a number of type double such as 5.345
double y = ceil(x);

In the above fragment, I used the new static import feature to import the static method ceil() from the Math class. Now when I call the method, I don't have to qualify it with Math. If I wanted to use multiple static methods from the Math class, I could import them individually or all at once as shown below:

// Import all static methods from Math
import static java.lang.Math.*;

This also applies to any constants declared within Math, such as E and PI. With the above declaration, I can use these constants as if they were declared locally within my class (or superclass).

Use it when you require frequent access to static members from one or two classes. 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. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.


Ricky Clarkson said...

"Readers of your code ... will not know which class a static member comes from."

What do you base this on? If I see a call to reallyImportantMethod, I just ctrl-click on it in any IDE and I'm at the declaration.

Even in a text editor or a web browser, I can just search for reallyImportantMethod. As long as I didn't use * imports, it's obvious where it came from because there's an import that explicitly references it.

Java programmer said...

Some cases I prefer to prefix name of Class but sometime it unnecessary bloat the code e.g.consider calling methods like assertNull from Junit as Assert.assertNull(), nothing wrong but I still like former one. Some more usecase discussed on where to use static import in Java


Popular Posts (Last 30 days)

This is a personal blog and I do not speak for my employer.