简体   繁体   English

groovy闭包的自动委托是什么?

[英]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". 在此页面的最后一个示例( http://groovy.codehaus.org/JN3525-MetaClasses )中,用于覆盖metaClass invokeMethod调用的关闭代码引用了一个“委托”。 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? 它似乎引用了Bird类,但是这如何适合Groovy闭包和整个语言的实现?

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? 它似乎引用了Bird类,但是这如何适合Groovy闭包和整个语言的实现?

To answer the above, it does refer to instance of Bird . 为了回答上述问题,它确实引用了Bird实例。 It acts similar to this operator but outside the context of the wrapped object denoted by this . 它的作用类似于this运算符,但在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. 如果您正在Groovy Console中运行,请在最后一个println处进行标记。 this operator represents the script on which you run the above code. this运算符表示您在其上运行以上代码的脚本。

In addition to the above explanation, do visit the links provided in my comment. 除了上述说明之外,请访问我评论中提供的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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