MapUtils.java
1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.glsx.utils;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.TreeMap;
/**
* @Description: 将实体类属性转为map
* @author fengzhi
* @version V1.0
*/
public class MapUtils {
public static TreeMap<String, String> transBean2Map(Object obj) {
if(obj == null){
return null;
}
TreeMap<String, String> map = new TreeMap<String, String>();
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();
String value = String.valueOf(getter.invoke(obj)) ;
map.put(key, value);
}
}
} catch (Exception e) {
System.out.println("transBean2Map Error " + e);
e.printStackTrace();
}
return map;
}
}