如果使用@delegatesto注释,如何将参数传递到闭合



如果我在此处更改groovy dsl doc中的代码。

在电子邮件中添加一些字符串" Hello World",例如此

email('hello world') { // change here
   from 'dsl-guru@mycompany.com'
   to 'john.doe@waitaminute.com'
   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
}

所以,如何修改班级电子邮件以获取字符串'Hello world'??

告诉编译,闭合将带有一个参数,您需要添加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文档"中的@ClusureParams注释。

是的,我找到了一种方法,但不是完美的。

简单

new EmailSpec(name)  // change to 

但是,我真的想使用Groovy函数调用(名称)来解决

最新更新