Reputation: 6451
I have an Object
and a Map
. I want to copy all the name / values in the Map to be property values in the Object
.
So, considering:
def tony
def map = [plenty: "66", none: "0", ...]
I want tony to have properties, plenty and none and for them to have corresponding values in the map
?
Any idea how to do this in a groovy way?
Upvotes: 0
Views: 758
Reputation: 14519
If tony
does not need to be from a specific class object, you can use Expando
:
m = [a:1, b:2, c:"foobar"]
e = new Expando(m)
assert e.c == "foobar"
Upvotes: 3
Reputation: 101032
You can use something like:
class Foo { }
def tony = new Foo()
def map = [plenty: "66", none: "0"]
map.each{ k, v -> tony.metaClass.setProperty k, v }
tony.properties.each { println "$it.key -> $it.value" }
Output:
none -> 0
class -> class Foo
plenty -> 66
Upvotes: 3