Chapter 5
[ 99 ]
Parameters and the doCall method
You will note from the preceding example that we check for whether
MethodMissingException has been thrown to determine whether the method call
was successful. Groovy calls to closure methods are always via a dynamic method
lookup. MethodMissingException is the exception that the Groovy runtime throws
whenever it can't find a match to the method/closure based on the parameters
being passed.
MethodMissingException that is thrown relates to the generated doCall() method
for the closure. We know that Groovy generates Closure classes for each closure
that we define in our code. Therefore, we can imagine that Groovy is generating the
following closure classes on our behalf for the previous examples:
- For a closure with no explicit parameter defined, we can expect a doCall
method that accepts varargs to be generated. So, doCall for this closure
will accept any parameter that we pass to it:
def defaultParams = { println it; }
class Closure1 extends groovy.lang.Closure{
def doCall(Object [] params ) {
}
}
closure1 = new Closure1()
closure1.doCall("hello")
closure1.doCall("hello",1,0.1)
- For a closure accepting only one dynamically typed parameter, we would
expect our doCall method to also accept a single parameter. We can pass any
value to this doCall method, but should expect an exception if we pass more
than one parameter:
def dynamicParams = { something -> println something; }
class Closure2 extends groovy.lang.Closure{
def doCall(something) {
}
}
closure2 = new Closure2()
closure2.doCall("hello")
closure2.doCall(1)
closure2.doCall("hello",1,0.1) // exception