Shorthand way for assigning object properties in Groovy?
15,395
Solution 1
You have the with
method, as described by the great Mr Haki
item1.with{
name = "hello"
weight = "175"
}
Solution 2
Yes, you can do it like this:
item1.metaClass.setProperties(item1, [name: "hello", weight: "175"])
Solution 3
I prefer item1.with if I have concrete variables to change
item1.with {
name = "lalal"
weight = 86
high = 100
}
I prefer InvokerHelper.setProperties when I have map of properties (can be any size)
@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"
Output:
before: Item(foo, 150)
after : Item(abc, 22)
Author by
raffian
Applications architect and code slinger since 2000, my background is full stack Java. Reach me at 72616666692e6970616440676d61696c2e636f6d My other passion is landscape photography, check it out if you're interested!
Updated on June 17, 2022Comments
-
raffian almost 2 years
I create Groovy objects using this convention...
Item item1 = new Item( name: "foo", weight: "150")
...is there a shorthand convention for manipulating properties object? something like this...
item1( name: "hello", weight: "175") //this does not work, btw ;-)
...instead of...
item1.name = "hello" item1.weight = "175"
-
Grooveek over 12 years@RaffiM for Groovy and Grails users, he is great. (his blog is great)
-
epidemian over 12 yearsYou may also do something like
[name: "hello", weight: "175"].each { item1[it.key] = it.value }
if the object does not override thesetAt
mehod or[name: "hello", weight: "175"].each { item1.setProperty it.key, it.value }
.