通过委托绑定时,Groovy闭包短格式方法调用不起作用?

Rod*_*Rod 5 groovy binding

我创建了一个代码示例,显示了我遇到的问题:

class BindingExample {

    public static void main(String[] args) {

        Closure closure1 = {
            printit.call("Hello from closure 1")
        }

        Closure closure2 = {
            printit("Hello from closure 2")
        }

        Closure printit = { s ->
            println("printing: "+s)
        }

        Binding binding = new Binding()
        binding.setVariable("printit", printit)

        closure1.delegate = binding
        closure2.delegate = binding

        closure1()  //This works fine
        closure2()  //This does not.  

        //Why does .call() work and () alone not?  Most documentation says they're the same.
    }

}
Run Code Online (Sandbox Code Playgroud)

为printit是一个Closure,其中文件指示器具doCall,因此在短形式可调用经由().

但是,当通过绑定到委托来使此闭包可用时,只允许调用的长格式版本.输出是:

printing: Hello from closure 1
Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: groovy.lang.Binding.printit() is applicable for argument types: (java.lang.String) values: [Hello from closure 2]
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么会这样吗?如果可能的话,我还想看看如何制作它,以便短版本的版本有效.我能够通过定义printit一个合适的静态方法(不是闭包)来使它工作,但这对我的情况不起作用,因为我实际上需要printit给出一些只在方法范围内可用的数据(不包含在这个例子,因为我的问题与绑定本身有关).

bil*_*dev 2

不幸的是,至于为什么会出现这种情况,我无法给出明确的答案。有一些关于隐式“this”注释等的讨论。看起来它应该可以工作,但是对于应该首先尝试什么(this-scope 或 delegate)存在一些模糊性。

目前,这个问题的存在似乎是正确的。我发现以下其他资源也同意这一点,其中有一些讨论但没有解决原因。

关于该问题的 Nabble 讨论: http://groovy.329449.n5.nabble.com/Binding-Closure-property-not- Called-as-method-td5562137.html

JIRA 票证结果: https://issues.apache.org/jira/browse/GROOVY-5367