Java examples for Reflection:Java Bean
bean To Map
//package com.java2s; import java.beans.BeanInfo; import java.beans.IntrospectionException; 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 <T> Map<?, ?> beanToMap(T bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException { Class<?> type = bean.getClass(); Map<String, Object> returnMap = new HashMap<String, Object>(); 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[] {}); if (result != null) { returnMap.put(propertyName, result); } else { returnMap.put(propertyName, ""); }//from w w w .j a v a 2 s .c o m } } return returnMap; } }