Map to Java Bean - Java Reflection

Java examples for Reflection:Java Bean

Description

Map to Java 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.InvocationTargetException;

import java.util.Map;

public class Main {
    public static <T> T toJavaBean(Map<String, ?> map,
            Class<T> javaBeanClazz) throws IntrospectionException,
            IllegalAccessException, InstantiationException,
            InvocationTargetException {
        BeanInfo beanInfo = Introspector.getBeanInfo(javaBeanClazz);
        PropertyDescriptor[] propertyDescriptors = beanInfo
                .getPropertyDescriptors();
        T obj = javaBeanClazz.newInstance();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (map.containsKey(propertyName)) {
                Object value = map.get(propertyName);
                descriptor.getWriteMethod().invoke(obj, value);
            }//  www  . jav a 2  s.  c  o  m
        }
        return obj;
    }
}

Related Tutorials