...
| Code Block |
|---|
import static java.awt.Color.LIGHT_GRAY
import static Boolean.FALSE as F
import static Calendar.getInstance as now
import static java.lang.Integer.*
println LIGHT_GRAY
// => java.awt.Color[r=192,g=192,b=192]
println !F
// => true
println now().time
// => Sun Apr 29 11:12:43 EST 2007
println "Integers are between $MIN_VALUE and $MAX_VALUE"
// => Integers are between -2147483648 and 2147483647
def toHexString(int val, boolean upperCase) {
def hexval = upperCase ? toHexString(val).toUpperCase() : toHexString(val)
return '0x' + hexval
}
println toHexString(15, true)
// => 0xF
println toHexString(15, false)
// => 0xf
|
The first static import illustrates defining LIGHT_GRAY as if it was defined locally as a static field.
The next two examples show renaming (called aliasing) of a field and a method respectively.
The final example illustrates wild-carding for fields and methods and also selecting between the locally defined toHexString and imported toHexString based on parameter matching.
...
| Code Block |
|---|
import static java.lang.Math.*
println sin(123.456) * cos(456.789)
// => 0.24733809349262376
|
Note: Groovy does not check beyond your import class if what you statically import exists. If you import a nonexisting method, field or property Groovy will not fail at compile time, but later when executing the compiled code.