我创建了一个代码示例,显示了我遇到的问题:
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.
}
}
Printit 是
Closure
,其中documentation表示实现了 doCall,因此可以通过 () 以简写形式调用。但是,当此闭包通过绑定(bind)到委托(delegate)而可用时,仅允许调用的长格式版本。输出是:
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]
有人可以解释为什么会这样吗?如果可能的话,我还想看看如何制作它,以便简短版本的工作。我能够通过定义
printit
使其工作作为一个适当的静态方法(不是闭包),但这不适用于我的情况,因为我实际上需要为 printit 提供一些仅在方法范围内可用的数据(不包括在示例中,因为我的问题与绑定(bind)有关本身)。
最佳答案
至于为什么会这样,很遗憾,我无法给出明确的答案。有一些关于隐式-“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
关于binding - 通过委托(delegate)绑定(bind)时,Groovy 闭包短格式方法调用不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15366385/