【问题标题】:Groovy Closure not checking owner or delegate scopeGroovy Closure 不检查所有者或委托范围
【发布时间】:2015-01-18 17:17:07
【问题描述】:

我正在写一个小的Groovy DSL,它依赖于Groovy Closures。然后我使用GroovyShellDelegatingScriptJava 程序运行DSL

从 Java 调用脚本的代码:

DelScript project = new DelScript ();

CompilerConfiguration cc = new CompilerConfiguration();
cc.setScriptBaseClass("groovy.util.DelegatingScript");
GroovyShell sh = new GroovyShell(Launcher.class.getClassLoader(), new Binding(), cc);

DelegatingScript script = (DelegatingScript) sh.parse(new File(path));
script.setDelegate(project);
script.run();

DelScript 的实例作为脚本内的 this 引用,例如在 DelScript 的实例中搜索脚本本身未找到的任何成员或方法。

我的脚本可以包含以下表达式:

create (name: "test") {
    // this code can be used to initialize the 
    // object that is created here
    testProperty = "I'm an example"
}

这段代码的目的是创建一个对象,然后调用闭包来初始化它。正如我之前所说,create 方法驻留在DelScript 实例中,(这是我想要的),它看起来像这样:

def create(arguments, configClosure) {
    // create new object
    def x = new Impl(arguments)

    // use configClosure to init it
    configClosure.delegate = x
    configClosure()
}

虽然我设置了configClosuredelegate,但我得到一个错误,表明testProperty 不是DelScript 的一部分。我知道DelScript 实例是configClosurethis,因为我在DelScript 范围内创建了它,但我认为闭包会按以下顺序检查引用:this -> owner -> delegate。在我的情况下,它从不检查 delegate,但在检查 this 后立即引发异常。

谁能给我一些关于我做错了什么的反馈?

【问题讨论】:

    标签: java groovy closures dsl


    【解决方案1】:

    行后

    configClosure.delegate = x
    

    configClosure.resolveStrategy = Closure.DELEGATE_FIRST
    

    【讨论】:

      猜你喜欢
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      相关资源
      最近更新 更多