简体   繁体   English

Groovy Closure不检查所有者或委托范围

[英]Groovy Closure not checking owner or delegate scope

I am writing a small Groovy DSL , which relies on Groovy Closures . 我正在编写一个依赖Groovy Closures的小型Groovy DSL I then run the DSL from a Java program by using GroovyShell and a DelegatingScript . 然后,我使用GroovyShellDelegatingScriptJava程序运行DSL

Code invoking the script from Java: 从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();

The instance of DelScript works as the this reference inside the script, eg any member or method not found in the script itself is searched in the instance of DelScript . DelScript实例用作脚本内的this引用,例如,在DelScript实例中搜索脚本本身中未找到的任何成员或方法。

My script can include the following expressions: 我的脚本可以包含以下表达式:

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

The intention of this code is to create an object and then call the closure, which can be used to initialize it. 这段代码的目的是创建一个对象,然后调用闭包,该闭包可用于初始化它。 As I said before, the create method resides in the DelScript instance, (which is what I want) and it looks like this: 如前所述, create方法位于DelScript实例中(这是我想要的),它看起来像这样:

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

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

Although I set the delegate of the configClosure , I get an error that testProperty is not a part of DelScript . 虽然我设置了delegate的的configClosure ,我得到一个错误 testProperty不是的一部分DelScript I know that the DelScript instance is the this of the configClosure , since I created it in the DelScript scope, but I thought that the closure would check references in the order: this -> owner -> delegate . 我知道DelScript实例是this的的configClosure ,因为我在创建它DelScript范围,但我认为关闭将检查顺序引用: this -> owner -> delegate It never checks delegate in my case but raises an exception right after checking this . 在我的情况下,它从不检查delegate ,但在检查this之后立即引发异常。

Can anyone give me some feedback on what I am doing wrong? 谁能给我一些我做错的反馈?

After the line 下线后

configClosure.delegate = x

Put

configClosure.resolveStrategy = Closure.DELEGATE_FIRST

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM