集册 Java实例教程 将Java Bean更改为Map

将Java Bean更改为Map

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

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


//package com.nowjava;

import java.beans.BeanInfo;

import java.beans.IntrospectionException;
/**
时 代 J     a    v  a - nowjava.com 提供 
**/

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 = "nowjava.com";

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

    }
//N  o w  J a v a . c o m 提供

    /**

     * change a JavaBean to a Map

     *

     */

    public static Map<String, String> convertBean(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();

                if (readMethod == null) {

                    continue;

                }

                Object result = readMethod.invoke(bean, 
展开阅读全文