Wednesday, January 2, 2013

Java 5 - Using Static Imports


Static Imports concept was introduced with Java 5, the static import statement just provides greater keystroke-reduction capabilities. Static imports can be used when you want to use a class's static members. You can use this feature on classes available in the API and on your own classes.

Rules associated with Static import


  • Correct syntax is import static, you can't say static import.
  • Check for ambiguously named static members. For example if you do a static import for both the Integer class and the Long class, referring to MAX_VALUE will cause a compiler error, since both Integer and Long have a MAX_VALUE constant, and Java won't know which MAX_VALUE you're referring to.
  • You can do a static import on static object references, constants (static and final), and static methods.


For example - 

Before static imports:

public class TestStatic {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.toHexString(42));
}
}

After static imports:

import static java.lang.System.out;
import static java.lang.Integer.*;

public class TestStaticImport {
public static void main(String[] args) {
out.println(MAX_VALUE); 
out.println(toHexString(42)); 
}
}

Both of the above classes produces same output.


Let's look at what's happening in the above code that's using the static import feature:

Even though the feature is commonly called static import the syntax MUST be "import static" followed by the fully qualified name of the static member you want to import, or a wildcard. In this case we're doing a static import on the System class out object and the static members of the java.lang.Integer class. Also We didn't have to type the System in System.out.println ( keystroke-reduction). Also, we didn't have to type the Integer in Integer.MAX_VALUE. So in this line of code we were able to use a shortcut for a static method AND a constant.

No comments:

Post a Comment