views:

46

answers:

1

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.

A: 

I found this: http://stackoverflow.com/questions/1370808/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)
Tihom
You could also do: `new User( myMap.findAll { k, v -> k in User.metaClass.properties*.name } )`
tim_yates