【发布时间】:2015-11-29 11:39:05
【问题描述】:
我是 Gradle/Groovy 的新手,在嵌套闭包中遇到变量名称解析问题。我有一个自定义任务类,它定义了一些属性,并且我正在使用闭包实例化该类型的多个任务。这个闭包定义了一个与自定义任务类中的一个属性同名的变量,我遇到了一些奇怪的行为,这似乎违背了 Groovy 语言指南中定义的内容。有人可以回答下面代码中的问题吗?
class Something extends DefaultTask {
def thing = "a"
}
/*
def thing = "b" // produces the error message:
// > Could not find method b() for arguments [build_63hfhkn4xq8gcqdsf98mf9qak$_run_closure1@70805a56] on root project 'gradle-test'.
// ...why?
*/
(1..1).each {
def thing = "c"
task ("someTask${it}", type: Something) {
println resolveStrategy == Closure.DELEGATE_FIRST // prints "true"
println delegate.class // prints "class Something_Decorated"
println thing // prints "c" shouldn't this be "a" since it's using DELEGATE_FIRST?
/*
println owner.thing // produces the error message:
// > Could not find property 'thing' on root project 'gradle-test'
// shouldn't the "owner" of this closure be the enclosing closure?
// in that case shouldn't this resolve to "c"
*/
}
}
编辑:
出于某种原因,在将所有 def 更改为 String 然后再改回 def 后,我无法再复制 def thing = "b" 行,从而产生奇怪的错误
【问题讨论】: