Power Groovy DSL Features
[ 172 ]
The Groovy runtime maintains a single MetaClass per Groovy class, and these
operate in close quarters with the GroovyObject interface. GroovyObject
implements a number of methods, which in their default implementations are
just facades to the equivalent MetaClass methods. The most important of these to
understand is the invokeMethod() method.
Pretended methods – MetaClass.invokeMethod
An important distinction between Java and Groovy is that, in Groovy, a method call
never invokes a class method directly. A method invocation on an object is always
dispatched in the first place to the GroovyObject.invokeMethod() method of the
object. In the default case, this is relayed onto the MetaClass.invokeMethod()
method for the class and MetaClass is responsible for looking up the actual method.
This indirect dispatching is the key to how a lot of Groovy power features work as it
allows us to hook ourselves into the dispatching process in interesting ways:
class Customer {
int id
String firstName
String surname
String street
String city
Object invokeMethod(String name, Object args) {
if (name == "prettyPrint") {
println "Customer has following properties"
this.properties.sort { it.key }.each {
if (it.key != 'class')
println " " + it.key + ": " + it.value
}
}
}
}
given:
def fred = new Customer(id:1001,firstName:"Fred",
surname:"Flintstone",
street:"1 Rock Road",city:"Bedrock")
def barney = new Customer(id:1002,firstName:"Barney",
surname:"Rubble",
street:"2 Rock Road",city:"Bedrock")
http://www.ebook3000.com