Set object fields from HashMap

forker picture forker · Jan 17, 2012 · Viewed 22.4k times · Source

Is there a library that can do the following?:

Given an Object and a HashMap, it enumerates the keys of the Hashmap and looks up the setters for these keys in the Object and sets the associated values. Something looking like that:

public Object setData(Object object, HashMap<String, Object> fields) {
   for (Entry<String, Object> entry : fields.entrySet()) {
      Method m = object.getClass().getMethod("set" + entry.getKey(), entry.getValue().getClass());
      if (m != null) {
         m.invoke(object, entry.getValue());
      }
   }
   return object;
}

The task looks simple at the first look but there are some nuances that I hope someone has already taken care of. As you know, reinventing the wheel (the good wheel) is a bad approach.

Answer

e-zinc picture e-zinc · Jan 17, 2012

Look at Apache Commons BeanUtils

org.apache.commons.beanutils.BeanUtils.populate(Object bean, Map properties)

Javadoc:
Populate the JavaBeans properties of the specified bean, based on the specified name/value pairs. This method uses Java reflection APIs to identify corresponding "property setter" method names, and deals with setter arguments of type String, boolean, int, long, float, and double.