Monday, March 16, 2009

Static Import!! Tiger.

Static Imports

The new 'import static' statement is another great addition to the language. As Java programmers, you may well have written code like the following on more than one occasion:

PrintStream o = System.out;
o.print("stuff");
o.print("more stuff");

The reference variable o is no more than a handy shortcut to System.out. In Java 5, you can import a class's static members and refer to them without the usual class name prefix. Thus, you can now do something like this:

import static java.lang.System.out;
// other code here.
out.print("stuff");
out.print("more stuff");

Once the static member is imported, you can use it in your code without the System class prefix. Here's an even better example from the GUI world of Swing.

// without static import.
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

// with static import.
import static javax.swing.WindowConstants.*;
// other code
setDefaultCloseOperation(EXIT_ON_CLOSE);

In the second example, the addition of the static import greatly enhances the readability of the code and cuts down on the amount of code required. I used the * to import all of WindowConstants static members in this case.

Blogged with the Flock Browser

No comments:

Post a Comment