我正在创建一个接受 Groovy 闭包作为标记的构建器。但是,我无法使用嵌套闭包捕获方法调用。
Closure nested = {
foo () //will throw missingMethod exception
}
Closure root = {
foo () //prints 'missing foo []'
inline_nested {
foo () //prints 'missing foo []'
}
nested ()
}
builder.execute (root)
// ...
class MyBuilder {
void execute (Closure closure) {
def clone = closure.clone()
clone.delegate = this
clone()
}
def missingMethod (String name, args) {
println "missing ${name} ${args}"
}
}
有什么方法可以为嵌套闭包设置委托(delegate)属性?
最佳答案
如果你想写一个builder,你应该考虑扩展BuilderSupport而不是自己从头开始编写。它负责将每个方法调用委托(delegate)给正确的对象。
Here's an example of a JSON builder I wrote通过扩展这个类。
关于groovy - 通过 Groovy 中的嵌套闭包传递委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5973786/