基于Groovy的DSL中绑定的奇怪行为

时间:2016-09-23 22:20:48

标签: groovy metaprogramming dsl

我有一个基于Groovy的DSL,其中我想从声明的绑定中访问变量。这是我的DSL实施:

class Bar {
    String barVal

    void bar(String bar) {
        this.barVal = bar
    }
}

class Foo {
    Bar bar

    void foo(@DelegatesTo(value = Bar, strategy = Closure.DELEGATE_FIRST) closure) {
        def bar = new Bar()
        def code = closure.rehydrate(bar, null, null)
        code()
        this.bar = bar
    }
}

abstract class MyScript extends Script  {

    Foo dslEntryPoint(@DelegatesTo(value = Foo, strategy = Closure.DELEGATE_FIRST) closure) {
        def foo = new Foo()
        def code = closure.rehydrate(foo, null, null)
        code()
        foo
    }
}

以下是我的DSL示例以及我如何运行它:

def DSL_NOT_WORKING = """
    dslEntryPoint() {
        foo {
            bar magicValue
        }
    }
"""

def DSL_OK = """
    def myMagicValue = magicValue
    dslEntryPoint() {
        foo {
            bar myMagicValue
        }
    }
"""

CompilerConfiguration config = new CompilerConfiguration(CompilerConfiguration.DEFAULT)
config.scriptBaseClass = MyScript.class.name
GroovyClassLoader groovyClassLoader = new GroovyClassLoader(getClass().getClassLoader(), config)
Class<Script> clazz = groovyClassLoader.parseClass(DSL_NOT_WORKING)
Binding binding = new Binding()
binding.setVariable('magicValue', '42')
Script script = InvokerHelper.createScript(clazz, binding)
Foo foo = script.run() as Foo
assert foo.bar.barVal == '42'

正如您所看到的,当我使用defDSL_OK)绑定变量时,我可以在我的DSL中访问它的值,否则(DSL_NOT_WORKING)我得到一个

java.lang.NullPointerException: Cannot get property 'magicValue' on null object

我做错了什么?如何在没有magicValue帮助声明的情况下访问变量def?我认为它与在闭包上调用rehydrate有关,我可以通过this而不是null,但这似乎不适用于嵌套对象层次结构(Foo-&gt;巴)。

谢谢, 迈克尔

1 个答案:

答案 0 :(得分:0)

问题在于我使用的rehydrate会覆盖所有者并使用null进行委托。而不是在嵌套对象层次结构中记录所有者和委托,而是简单地使用普通委托来简化:

Foo dslEntryPoint(@DelegatesTo(Foo) closure) {
  Foo foo = new Foo()
  closure.delegate = foo
  closure.call()
  foo
}