0

如果我有一个附加到扩展的闭包,并且闭包引用了扩展上的值,就像这样......

def e = new Expando()
e.val = 'hi'
e.doit = { println delegate.val }
e.doit()

它工作正常。并打印“嗨”

如果我用长格式调用闭包

e.doit.call()​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

它抛出一个错误

groovy.lang.MissingPropertyException: No such property: val for class: Script1
at Script1$_run_closure1.doCall(Script1.groovy:4)
at Script1$_run_closure1.doCall(Script1.groovy)
at Script1.run(Script1.groovy:6)

发生这种情况是因为委托从 e 更改为脚本。为什么?我认为 e.doit() 和 e.doit.call() 应该是相同的。

我可以手动更改委托 - 就像这样

def e = new Expando()
e.val = 'hi'
e.doit = { println delegate.val }
e.doit.delegate=e;
e.doit.call()​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

关于如何跳过代表的显式设置的任何想法?

4

1 回答 1

1

是的,有一个更好的主意。

当您知道自己定义了一个闭包(动态方法)时,请直接参考 Expando 实例(而不是委托),该闭包Expando只不过是一个动态 bean。另一方面,当针对具体类进行测试时,相同的测试会产生预期的结果:

def e = new Expando()
e.val = 'hi'
e.doit = {
    println delegate.class.name
    "$e.val Joseph"
}

assert e.doit() == 'hi Joseph'
assert e.doit.call() == 'hi Joseph'

class Test{
    String a
    def printA = {
        println delegate.class.name
        "$delegate.a Joseph"
    }
}
def test = new Test(a: 'hi')

assert test.printA() == 'hi Joseph'
assert test.printA.call() == 'hi Joseph'

注意系统println在这两种情况下。

于 2013-06-28T01:27:23.200 回答