2016-06-14 82 views
0

如果我在這裏更改Groovy DSL Doc中的代碼。如何使用@DelegatesTo註解將參數傳遞給閉包?

添加一些字符串「世界你好」,以電子郵件,這樣

email('hello world') { // change here 
    from '[email protected]' 
    to '[email protected]' 
    subject 'The pope has resigned!' 
    body { 
     p 'Really, the pope has resigned!' 
    } 
} 

,改變

def email(def name, @DelegatesTo(EmailSpec) Closure cl) { // change here 
    def email = new EmailSpec() 
    def code = cl.rehydrate(email, this, this) 
    code.resolveStrategy = Closure.DELEGATE_ONLY 
    code.call(name) // change here 
} 

那麼,如何修改類EmailSpec得到字符串'你好世界?

回答

0

是的,我找到了一種方式,但並不完美。

簡單

new EmailSpec(name) // change to 

不過,我真的想用常規的函數調用(名)解決它

0

告訴編譯的關閉將有一個參數叫你需要添加ClosureParams註釋。

要堅持自己的例子:

def email(def name, 
     @ClosureParams(value = SimpleType, options = "java.lang.String") 
     @DelegatesTo(EmailSpec) Closure cl) { 
    def email = new EmailSpec() 
    def code = cl.rehydrate(email, this, this) 
    code.resolveStrategy = Closure.DELEGATE_ONLY 
    code.call(name) // change here 
} 

會告訴編譯器,第一個參數是String

有關更多詳細信息,請參閱groovy文檔中的The @ClosureParams annotation部分。