import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.PropertyUtilsBean; public class Conversion { /** * 通过Java反射的机制动态的获取bean中的值,比较繁琐,后面有一个更简单的方法去做这些工作 * @param bean * @return * @throws Exception */ public static Map conversionToMap (T bean) throws Exception { Map map = new HashMap(); Class classType = bean.getClass(); Field[] fields = classType.getDeclaredFields(); for (Field f : fields) { String fieldName = f.getName(); if (!"serialVersionUID".equals (fieldName) ) { String strLetter = fieldName.substring (0, 1).toUpperCase(); String getName = "get" + strLetter + fieldName.substring (1); Method getMethod = classType.getMethod (getName, new Class[] {}); Object methodReturn = getMethod.invoke (bean, new Object[] {}); String value = methodReturn == null ? "" : methodReturn .toString(); map.put (fieldName, value); } } return map; } /** * 这里我们使用了第三方的工具类,可以帮之我们省去很多工作量,例如我们不需要自己通过反射的方法去获取bean中 * 属性的值,PropertyUtilsBean可以帮我们搞定一切 * @param bean * @return * @throws Exception */ public static Map conversionToMapByTool (T bean) throws Exception { Map map = new HashMap(); PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors (bean); for (PropertyDescriptor d : descriptors) { String fieldName = d.getName(); Object value = propertyUtilsBean.getNestedProperty (bean, fieldName); if (!"class".equals (fieldName) ) { map.put (fieldName, value); } } return map; } public static void main (String[] args) throws Exception { TestBean bean = new TestBean(); bean.setAddress ("Addrss"); bean.setName ("Name"); bean.setSex ("Man"); try { Map map1 = Conversion.conversionToMap (bean); System.out.println (map1.toString() ); Map map2 = Conversion.conversionToMapByTool (bean); System.out.println (map2.toString() ); } catch (Exception e) { e.printStackTrace(); } } }