public static voidmain(String[] args){
UserTest userTest= new UserTest("ceshi",25,234.5);
Map dataMap =beanToMap(userTest);
dataMap.forEach((k,v)->System.out.println("key:" + k + " val:" +v));
}public static MapbeanToMap(Object obj) {
Map params = new HashMap<>(0);try{//方法一
/*PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
for (int i = 0; i < descriptors.length; i++) {
String name = descriptors[i].getName();
if (!"class".equals(name)) {
params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
}
}*/
//方法二
/*BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors){
String key = propertyDescriptor.getName();
if(!key.equals("class")){
Object value = propertyDescriptor.getReadMethod().invoke(obj);
params.put(key,value == null ? "" : value);
}
}*/
//方法三
if (obj != null) {
BeanMap beanMap=BeanMap.create(obj);for(Object key : beanMap.keySet()) {
params.put(key+"", beanMap.get(key));
}
}
}catch(Exception e) {
e.printStackTrace();
}returnparams;
}