简体   繁体   中英

What is the automatic delegate of a groovy closure?

In the last example of this page ( http://groovy.codehaus.org/JN3525-MetaClasses ), the closure code to override the metaClass invokeMethod call refers to a "delegate". Code is also copied below:

class Bird{
  def name= 'Tweety'
  def twirp(){ 'i taught i saw a puddy cat' }
}
Bird.metaClass.invokeMethod= {name, args->
  def metaMethod= Bird.metaClass.getMetaMethod(name, args) 
        //'getMetaMethod' gets method, which may be an added or an existing one
  metaMethod? metaMethod.invoke(delegate,args): 'no such method'
}
def a= new Bird()
assert a.twirp() == 'i taught i saw a puddy cat'
assert a.bleet() == 'no such method'

Bird.metaClass.getProperty= {name->
  def metaProperty= Bird.metaClass.getMetaProperty(name) 
    //'getMetaProperty' gets property, which may be an added or an existing one
  metaProperty? metaProperty.getProperty(delegate): 'no such property'
}
def b= new Bird()
assert b.name == 'Tweety'
assert b.filling == 'no such property'

Where exactly is the delegate coming from and two what does it refer to?

It seems to refer to the Bird class, but how does this fit into Groovy closures and the implementation of the language as a whole?

It seems to refer to the Bird class, but how does this fit into Groovy closures and the implementation of the language as a whole?

To answer the above, it does refer to instance of Bird . It acts similar to this operator but outside the context of the wrapped object denoted by this . This can be explained with a small example:

Integer.metaClass.sayHello = {
    return "Say hello $delegate times"
}

assert 2.sayHello() == "Say hello 2 times" 
assert 20.sayHello() == "Say hello 20 times" 


Integer.metaClass.sayHi = {
    return "Say hello $this times"
}

println 2.sayHi()

Mark at the last println if you are running in Groovy Console. this operator represents the script on which you run the above code.

In addition to the above explanation, do visit the links provided in my comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM