提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
将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,