//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, new Object[0]);
/**代码未完, 请加载全部代码(NowJava.com).**/
本文系作者在时代Java发表,未经许可,不得转载。如有侵权,请联系nowjava@qq.com删除。