Convert Java bean to Map - Java Reflection

Java examples for Reflection:Java Bean

Description

Convert Java bean to Map

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.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object bean = "java2s.com";
        System.out.println(bean2Map(bean));
    }/*ww w  .j av a  2s  . c  o m*/

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Map bean2Map(Object bean) throws IntrospectionException,
            IllegalAccessException, InvocationTargetException {
        Class type = bean.getClass();
        Map returnMap = new HashMap();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors = beanInfo
                .getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptors.length; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (!propertyName.equals("class")) {
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean, new Object[0]);
                // System.out.println(descriptor.getName()+"---"+descriptor.getPropertyType().getSimpleName());
                if (result != null) {
                    returnMap.put(propertyName, result);
                } else {
                    switch (descriptor.getPropertyType().getSimpleName()) {
                    case "String":
                        returnMap.put(propertyName, "");
                        break;
                    case "Integer":
                        returnMap.put(propertyName, 0);
                        break;
                    case "Long":
                        returnMap.put(propertyName, 0l);
                        break;
                    case "BigDecimal":
                        returnMap.put(propertyName, 0);
                        break;
                    case "int":
                        returnMap.put(propertyName, 0);
                        break;
                    case "float":
                        returnMap.put(propertyName, 0f);
                        break;
                    case "double":
                        returnMap.put(propertyName, 0d);
                        break;
                    default:
                        returnMap.put(propertyName, null);
                    }

                }
            }
        }
        return returnMap;
    }
}

Related Tutorials