在此页面的最后一个示例 ( http://groovy.codehaus.org/JN3525-MetaClasses ) 中,覆盖 metaClass invokeMethod 调用的闭包代码引用了“委托”。代码也复制如下:
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'
代表究竟来自哪里,两个它指的是什么?
它似乎是指 Bird 类,但它如何适应 Groovy 闭包和整个语言的实现?