Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set object fields from HashMap

Tags:

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.

like image 671
forker Avatar asked Jan 17 '12 14:01

forker


People also ask

Can we create custom object in HashMap?

If you want to make a mutable object as a key in the hashmap, then you have to make sure that the state change for the key object does not change the hashcode of the object. This can be done by overriding the hashCode() method. But, you must make sure you are honoring the contract with equals() also.

What is values () in HashMap in Java?

values() method of HashMap class in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap.

Can we use class object as key in HashMap?

We can conclude that to use a custom class for a key, it is necessary that hashCode() and equals() are implemented correctly. To put it simply, we have to ensure that the hashCode() method returns: the same value for the object as long as the state doesn't change (Internal Consistency)


2 Answers

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.

like image 62
e-zinc Avatar answered Sep 19 '22 06:09

e-zinc


Better use BeanUtils class:

public Object setData(Object object, HashMap<String, Object> fields) {
   for(Entry<String, Object> entry : fields.entrySet()) {
      BeanUtils.setProperty(object, entry.getKey(), entry.getValue());
   }
   return object;
}
like image 29
Funky coder Avatar answered Sep 19 '22 06:09

Funky coder