restore Java Bean Properties - Java Reflection

Java examples for Reflection:Java Bean

Description

restore Java Bean Properties

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 a  v a 2s.  c o m
            BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
            PropertyDescriptor[] descriptors = beanInfo
                    .getPropertyDescriptors();
            for (PropertyDescriptor des : descriptors) {
                String fieldName = des.getName();
                if (propMap.containsKey(fieldName)) {
                    Method setter = des.getWriteMethod();
                    setter.invoke(bean,
                            new Object[] { propMap.get(fieldName) });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials