map To Bean - Java Reflection

Java examples for Reflection:Java Bean

Description

map To Bean

Demo Code


//package com.java2s;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

import java.lang.reflect.Method;

import java.util.Map;

public class Main {

    public static <T> T mapToBean(Map<?, ?> map, Class<T> bean)
            throws InstantiationException, IllegalAccessException,
            IntrospectionException {
        BeanInfo beanInfo = Introspector.getBeanInfo(bean);
        T obj = bean.newInstance();/*from   w w w  . ja va  2s. c o  m*/
        PropertyDescriptor[] propertyDescriptors = beanInfo
                .getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            Method method = descriptor.getWriteMethod();
            String name = descriptor.getName();
            if (map.containsKey(name)) {
                Class<?>[] types = method.getParameterTypes();
                for (int x = 0; x < types.length; x++) { //
                    Object value = map.get(name);
                    try {
                        method.invoke(obj, new Object[] { value });
                    } catch (Exception e) {
                        System.out.println("type:"
                                + types[x].getSimpleName() + "|name:"
                                + name + "|value:" + value);
                        e.printStackTrace();
                    }
                }
            }
        }
        return obj;
    }
}

Related Tutorials