groovy - 通过 Groovy 中的嵌套闭包传递委托(delegate)

标签 groovy metaprogramming expandometaclass

我正在创建一个接受 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/

相关文章:

grails - Grails 中的 ExpandoMetaClass 是否可以覆盖 Java 库中的行为?

unit-testing - 覆盖 Grails GORM 域类上的事件关闭以进行单元测试

grails - 运行应用程序和运行 war 之间的Grails行为差异

Jenkins groovy 管道 - 检索构建作业的构建号

c# - 在 C# 中确定对象 o 是 Action<...> 还是 Func<....>

grails - 在grails Controller 中关闭不接受参数

python - 在 Python 的 __getitem__ 方法中使用关键字参数

ruby - 在 Ruby 中动态定义类方法

java - Groovy:list.pop() 不起作用

html - Groovy/Grails Hibernate 无法创建 bean 事务