0

I have a hashMap as below

Map<String, Object> attributes = new HashMap<String, Object> {
    {
        put("type", "A");
        put("duration", 10);
        put("isSet", true);
    }
}

Now I would like to populate an object with these values. How do I invoke the setters in a for loop instead of manually calling each method. Say I want to populate an object ob with these properties.

Sunil
  • 856
  • 12
  • 24
  • 1
    Please don't do this unless you really have to. You should call the set-methods properly instead. – marstran Sep 14 '16 at 11:54
  • I agree, you shouldn't do this, if you want that to avoid a lot of code try Builder Pattern. – Shadov Sep 14 '16 at 11:57

1 Answers1

2

You can simply use the java beans standard:

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public void populateValues(Object bean, Map<String, Object> propertyValues) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    BeanInfo beanInfo = Introspector.getBeanInfo(Pojo.class);
    for(PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
        if(pd.getWriteMethod() != null && propertyValues.containsKey(pd.getName())) {
            pd.getWriteMethod().invoke(bean, propertyValues.get(pd.getName()));
        }
    }
}

Note that this shouldn't generally be used to avoid calling setters. It is only handy if you already have a map containing such entries from somewhere else.

Also note that this implementation is not compatible with the entry isSet=true. It would require an entry key named set.

You might really want to look at the builder pattern. If using java 8, you might be interested in a more general way to implement the builder pattern as shown in this answer of me.

Community
  • 1
  • 1
SpaceTrucker
  • 13,377
  • 6
  • 60
  • 99