我有两个特质
trait Mapping {
@Delegate
Map map = new LinkedHashMap()
}
trait Weight {
private Closure weight
int getWeight() {
weight.delegate = this
weight.call()
}
def weight(Closure c) {
weight = c
}
}
当我将它们应用于对象时,我无法将权重作为属性object.weight
我需要调用object.getWeight()
。有没有办法改变特征,object.weight
有效。
这是我想要尝试的测试。
def 'test traits'() {
setup:
def object = new Object()
when:
object = object.withTraits(Mapping, Weight)
object.key = 'value'
object.weight { 100 }
then:
object.key == 'value'
object.weight == 100
}
答案 0 :(得分:1)
您可以将Mapping
特征更改为:
trait Mapping {
Map map = [:]
def propertyMissing(String name) {
map[name]
}
def propertyMissing(String name, value) {
map[name] = value
}
}