将一个java对象的属性值转换为一个Map:
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public Map<String, Object> transBean2Map(Object obj) { if(obj == null){
return null;
} Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName(); // 过滤class属性
if (!"class".equals(key)) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
logger.info("获取到的getter为------>{}",getter);
Object value = getter.invoke(obj);
logger.info("获取到的key为----->{},value为----->{}",key,value);
map.put(key, value);
} }
} catch (Exception e) {
System.out.println("transBean2Map Error " + e);
e.printStackTrace();
} return map;
}