Thursday, March 27, 2008

Static Import - Java 5

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:

 

 

No comments:

Post a Comment