Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 166 ]

A neat trick with expandos is what happens when we store a closure in a property.
As we would expect, an Expando closure property is accessible in the same way as a
normal property. However, because it is a closure, we can apply function call syntax
to it to invoke the closure. This has the effect of seeming to add a new method on the
fly to the Expando:


customer.prettyPrint = {
println "Customer has following properties"
customer.properties.sort {it.key} .each {
if (it.key != 'prettyPrint')
println " " + it.key + ": " + it.value
}
}

customer.prettyPrint()

Here we appear to be able to add a prettyPrint() method to the customer object,
which outputs to the console:


Customer has following properties


surname: Flintstone


street: 1 Rock Road


firstName: Fred


id: 1001


Categories


Adding a closure to an Expando to give a new method is a useful feature, but what
if we need to add methods to an existing class on the fly? Groovy provides another
useful feature—categories—for this purpose. A Category can be added to any class
at runtime, by using the use keyword.


We can create Category classes that add methods to an existing class. To create
a Category for a class, we define a class containing static methods that take an
instance of the class that we want to extend as their first parameter. By convention,
we name this parameter as self. When the method is invoked, self is set to the
object instance that we are extending. The Category can then be applied to any
closure by using the use keyword.


http://www.ebook3000.com
Free download pdf