Tihom
Tihom

Reputation: 3394

Groovy: Setting property values easily

I have a map with name/value pairs:

def myMap = [
  "username"  : "myname",
  "age" : 30,
  "zipcode" : 10010
]

I have a class called User defined:

class User {
  def username;
  def age;
  def zipcode;
}

I would like to invoke the appropriate setters on the bean. Is there a nice groovy way of doing this? Note, I might have extra stuff in the myMap that wouldn't be set. (The map is a form parameter values map)

I was thinking about using invokeMethod but I was assuming there was a better way.

Upvotes: 1

Views: 2965

Answers (1)

Tihom
Tihom

Reputation: 3394

I found this: Groovy - bind properties from one object to another

And I realized I could do the following:

def prunedMap = [:]
myMap.each{
    if (User.metaClass.properties.find{p-> p.name == it.key}) {
        prunedMap.put(it.key, it.value)
    }
}

User user = new User(prunedMap)

Upvotes: 3

Related Questions