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.