I have some noob questions about delegate in groovy meta programming.
with this line of code
grailsApplication.domainClasses.each { gdc ->
def domClass = gdc.clazz
domClass.metaClass.invokeMethod{name,args ->
//some line of code
def result = invokeMethod(delegate,args)
}
}
what is the content of delegate, name and args in here ?
In general, what is delegate and what kind contents does it has ?
Any help and explanation will be appreciated
You have a typo;
domClass.metaClass.invokeMethod{name,args ->should bedomClass.metaClass.invokeMethod = { String name,args ->. This is assigning a Closure to be the handler for all method calls on that class. Since you’re handling method calls, you’ll need to know the name of the method and the method arguments, so those are the parameters of the closure. Theargsparameter will be anObject[]array containing the args from the method invocation. So for exampledomClass.foo()will have name “foo” and an emptyargsarray,domClass.foo("purple")will have a 1-element array containing the String “purple”, etc.Think of
delegateasthisinside the closure.thisis actually the class instance that the Closure is defined in, not the closure itself or the object that the method is being called on. Since you’ll often need the object,delegatepoints to it. Ordinarily the delegate will be the containing instance where the closure is defined, so method calls are resolved by looking there, and if not found, a missing method exception is thrown. But you can set the delegate to be another handler which has the methods that are being called, and it will be delegated to instead. This is particularly useful with Groovy builders and DSLs.