2016-09-23 49 views
1

我有一個基於Groovy的DSL,我想從聲明的綁定中訪問變量。這是我的DSL實現:在基於Groovy的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 

我在做什麼錯?如何在沒有def幫助器聲明的情況下訪問變量magicValue?我認爲這與在關閉時調用rehydrate有關,我可以通過this而不是null,但這似乎不適用於嵌套對象層次結構(Foo-> Bar)。

感謝, 邁克爾

回答

0

問題是我的rehydrate使用它覆蓋所有者,並與null委派。代替在嵌套對象層次結構中記錄所有者和委託,只需使用普通委託代替就簡單多了:

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