集册 Java实例教程 将Java bean转换为Map

将Java bean转换为Map

欢马劈雪     最近更新时间:2020-01-02 10:19:05

415
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将Java bean转换为Map


//package com.nowjava;

import java.beans.BeanInfo;

import java.beans.IntrospectionException;
/** 
 来自 时代Java公众号**/

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 {/* from n  o  w  j  a  v  a . c o m*/

    public static void main(String[] argv) throws Exception {

        Object bean = "nowjava.com";

        System.out.println(bean2Map(bean));

    }


    @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);

                        
展开阅读全文