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

将Java Bean转换为Map

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

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


//package com.nowjava;
/*来自 
 n o w j a v a . c o m - 时  代  Java*/

import java.beans.BeanInfo;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Method;

import java.util.LinkedHashMap;

import java.util.Map;


public class Main {

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

        Object obj = "nowjava.com";

        System.out.println(transBean2Map(obj));

    }


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

        if (obj == null) {

            return null;

        }

        Map<String, Object> map = new LinkedHashMap<String, Object>();
        /*
        NowJava.com - 时  代  Java
        */

        try {

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

            PropertyDescriptor[] propertyDescriptors = beanInfo

                    .getPropertyDescriptors();

            for (PropertyDescriptor property : propertyDescriptors) {

                String key = property.getName();

                // ??class??

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

                    // ??property???getter??

                    Method getter = property.getReadMethod(
展开阅读全文