在Groovy中分配对象属性的简写方法?

时间:2011-12-14 16:12:52

标签: class object groovy variable-assignment

我使用此约定创建Groovy对象...

Item item1 = new Item( name: "foo", weight: "150")

...是否存在操作属性对象的简写约定?像这样......

item1( name: "hello", weight: "175") //this does not work, btw ;-)

......而不是......

item1.name = "hello"
item1.weight = "175"

3 个答案:

答案 0 :(得分:20)

您拥有with方法,as described by the great Mr Haki

item1.with{
    name = "hello"
    weight = "175"
}

答案 1 :(得分:3)

是的,你可以这样做:

item1.metaClass.setProperties(item1, [name: "hello", weight: "175"])

答案 2 :(得分:2)

如果我要更改具体变量

,我更喜欢 item1.with
item1.with {
    name = "lalal"
    weight = 86
    high = 100
}

当我有属性地图(可以是任何大小)时,我更喜欢 InvokerHelper.setProperties

@ToString
class Item{
    def name
    def weight
}
Item item1 = new Item( name: "foo", weight: "150")

println "before: $item1"
use(InvokerHelper) {
    item1.setProperties weight: 22, name: "abc"
}
println "after : $item1"

输出:

before: Item(foo, 150)
after : Item(abc, 22)