Lmxy1990 ' Blog

使用反射将Object转换为HashMap

代码

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
public class MapUtils {


/**
* 使用反射获取对象的成员名作为key,值作为value
*
* @param o
* @return
*/
public static Map<String, String> objectField2Map(Object o) {
Map<String, String> result = new HashMap<>();
if (o == null) return result;
Class oClass = o.getClass();
Field[] fields = oClass.getDeclaredFields() ;
String key;
String value;
if (fields != null && fields.length != 0) {
for (Field field : fields) {
try {
key = field.getName();
if ("serialVersionUID".equalsIgnoreCase(key)) continue;
field.setAccessible(true);
Object o1 = field.get(o) ;
value = o1.toString();
result.put(key, value);
} catch (IllegalAccessException e) {
continue;
}
}
}
return result;
}
}

End

坚持原创技术分享,您的支持将鼓励我继续创作!