//package com.nowjava;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
/**
来自 时代Java公众号**/
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 {/* from n o w j a v a . c o m*/
public static void main(String[] argv) throws Exception {
Object bean = "nowjava.com";
System.out.println(bean2Map(bean));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map bean2Map(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();
Object result = readMethod.invoke(bean, new Object[0]);
// System.out.println(descriptor.getName()+"---"+descriptor.getPropertyType().getSimpleName());
if (result != null) {
returnMap.put(propertyName, result);
} else {
switch (descriptor.getPropertyType().getSimpleName()) {
case "String":
returnMap.put(propertyName, "");
break;
case "Integer":
returnMap.put(propertyName, 0);
break;
case "Long":
returnMap.put(propertyName, 0l);
break;
case "BigDecimal":
returnMap.put(propertyName, 0);
break;
case "int":
returnMap.put(propertyName, 0);
break;
case "float":
/**代码未完, 请加载全部代码(NowJava.com).**/
本文系作者在时代Java发表,未经许可,不得转载。如有侵权,请联系nowjava@qq.com删除。