集册 Java实例教程 将Bean转换为地图

将Bean转换为地图

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

502
将Bean转换为地图


//package com.nowjava;

import java.beans.BeanInfo;/*来 自 nowjava.com - 时代Java*/

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Method;

import java.util.HashMap;

import java.util.Map;


public class Main {



    @SuppressWarnings("unchecked")

    public static Map<String, Object> transBean2Map(Object obj) {

        if (obj instanceof Map) {

            return (Map<String, Object>) obj;

        }

        if (obj == null) {

            return null;

        }

        Map<String, Object> map = new HashMap<String, Object>();
        /** 
        来 自 
        n o w j a   v  a . c o m - 时  代  Java
        **/

        try {

            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());

            PropertyDescriptor[] propertyDescriptors = beanInfo

                    .getPropertyDescriptors();

            for (PropertyDescriptor property : propertyDescriptors) {

                String key = property.getName();

  

                if (!key.equals("class")) {

                    Method getter = property.getReadMethod();

                    
展开阅读全文