我有一个基于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'
正如您所看到的,当我使用def
(DSL_OK
)绑定变量时,我可以在我的DSL中访问它的值,否则(DSL_NOT_WORKING
)我得到一个
java.lang.NullPointerException: Cannot get property 'magicValue' on null object
我做错了什么?如何在没有magicValue
帮助声明的情况下访问变量def
?我认为它与在闭包上调用rehydrate
有关,我可以通过this
而不是null
,但这似乎不适用于嵌套对象层次结构(Foo-&gt;巴)。
谢谢, 迈克尔
答案 0 :(得分:0)
问题在于我使用的rehydrate
会覆盖所有者并使用null
进行委托。而不是在嵌套对象层次结构中记录所有者和委托,而是简单地使用普通委托来简化:
Foo dslEntryPoint(@DelegatesTo(Foo) closure) {
Foo foo = new Foo()
closure.delegate = foo
closure.call()
foo
}