translate Map to Java Bean - Java Reflection

Java examples for Reflection:Java Bean

Description

translate Map to Java Bean

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 transMap2Bean(Map<String, Object> map, Object obj) {
        try {/*from   ww w.  j av  a2 s  . c o  m*/
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo
                    .getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();

                if (map.containsKey(key)) {
                    Object value = map.get(key);
                    // ??property???setter??
                    Method setter = property.getWriteMethod();
                    setter.invoke(obj, value);
                }
            }

        } catch (Exception e) {
            System.out.println("transMap2Bean Error " + e);
        }
        return;
    }
}

Related Tutorials