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