restore Java Bean Property - Java Reflection

Java examples for Reflection:Java Bean

Description

restore Java Bean Property

Demo Code


//package com.java2s;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import java.util.Map;

public class Main {
    public static void restoreProp(Object bean, Map<String, Object> propMap) {
        try {/*from w w  w . j av a  2  s.  co  m*/
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo
                    .getPropertyDescriptors();
            for (PropertyDescriptor descriptor : propertyDescriptors) {
                String fieldName = descriptor.getName();
                if (propMap.containsKey(fieldName)) {
                    Method writeMethod = descriptor.getWriteMethod();
                    writeMethod.invoke(bean,
                            new Object[] { propMap.get(fieldName) });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials