【发布时间】:2015-10-09 09:52:51
【问题描述】:
Groovy 版本:2.4.3 JVM:1.8.0_60 供应商:Oracle Corporation 操作系统:Mac OS X
import groovy.transform.*
@Canonical
class A {
def f() {
map = [:] //map is not null
3.times {
assert map != null // failed, map is null?!
}
}
@Delegate
Map map
}
new A().f()
当我调用 f() 时,我得到一个断言失败,这意味着 map 为空。但是如果我删除注释'@Delegate',那么就不会有任何问题。或者,如果断言不在闭包中,也没有问题。我的问题是为什么委派字段在闭包内外表现不同?如果是因为闭包中的map不是A类中的同一个对象,为什么在注释删除后它仍然有效?
import groovy.transform.*
@Canonical
class A {
def f() {
map = [:]
3.times {
assert map != null // No problem, map is not null
}
}
Map map
}
new A().f()
或者
import groovy.transform.*
@Canonical
class A {
def f() {
map = [:]
assert map != null //no problem too
}
@Delegate
Map map
}
new A().f()
【问题讨论】:
标签: groovy annotations closures