改善地图特征

时间:2017-05-04 10:49:05

标签: groovy

我有两个特质

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
}

1 个答案:

答案 0 :(得分:1)

您可以将Mapping特征更改为:

trait Mapping {
    Map map = [:]

    def propertyMissing(String name) {
        map[name]
    }

    def propertyMissing(String name, value) {
        map[name] = value
    }
}