我使用此约定创建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"
答案 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.withitem1.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)