2016-06-14 46 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部分。