Tuesday, June 28, 2011

Groovier Static Import

The introduction of the static import with J2SE 5 has provided some advantages. For example, I like it for specifying import static java.lang.System.out in my simple Java classes so that I can access the standard output stream easily with the out handle. (Cay Horstmann's Are you using static import? talks more about this use of static import.) In this blog post, I look at how Groovy supports Java's static import and adds more features to it to make it even more useful for concise and highly readable scripts.

The following simple Groovy script demonstrates use of Groovy's static import. One case prints out the value of Math.PI using both traditional Java regular import support and traditional Java static import support. The other examples are all Groovy and demonstrate how Groovy's static import even allows method calls to be referenced by constants defined with a Groovy static import. I attempted to place enough comments in this script to help show off Groovy's various static import features.

demonstrateGroovyStaticImport.groovy
#!/usr/bin/env groovy
/**
 * demonstrateGroovyStaticImport.groovy
 *
 * This script demonstrates Groovy's static import support. See Groovy Users
 * Guide at http://groovy.codehaus.org/Static+Import+Usage for additional
 * details and examples.
 *
 * http://marxsoftware.blogspot.com
 */

// Specify Calender.getInstance() as "present" (Groovy feature)
import static Calendar.getInstance as current
println "Now is: ${current().format("yyyy-MM-dd HH:mm:ss.SSSZ")}"

// Specify another constant to represent Boolean.FALSE (Groovy feature)
import static Boolean.FALSE as UNTRUE
println "UNTRUE is ${UNTRUE}"

// Specify another name for color WHITE (Groovy feature)
import static java.awt.Color.WHITE as POLAR_BEAR_COLOR
println "Polar Bear's color is ${POLAR_BEAR_COLOR}"

// Invoke Math constants directly without need to scope them explicitly (J2SE 5 feature)
import static java.lang.Math.*
println "PI is ${PI} (${Math.PI})"
println "E is ${E}"

// Invoke Math operations directly without need to scope them explicitly
println "2^5 = ${pow(2,5)}"
println "Square root of 256 = ${sqrt(256)}"

The output from running the above script is shown in the next screen snapshot.


Conclusion

Not everyone is a fan of Java's static import, but I think they it does have its time and place (the documentation states to use it very sparingly). Groovy's feature-rich static imports can make for more readable scripts when used appropriately.

No comments: