MapUtil.java
1.9 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.zteits.pay.weixin.util;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
/***
*
* Copyright: Copyright (c) 2017 ZTE-ITS
*
* @ClassName: MapUtil.java
* @Description: map object互转
* @version: v1.0.0
* @author: wangbiao
* @date: 2017年5月16日 上午10:13:08
* Modification History:
* Date Author Version Description
*---------------------------------------------------------*
* 2017年5月16日 wangbiao v1.0.0 创建
*/
public class MapUtil {
/**
* object转map
* @param obj
* @return
* @throws Exception
*/
public static Map<String, String> objectToMap(Object obj) throws Exception {
if(obj == null){
return null;
}
Map<String, String> map = new HashMap<String, String>();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
map.put(field.getName(), (String) field.get(obj));
}
return map;
}
/***
* map转object
* @param map
* @param beanClass
* @return
* @throws Exception
*/
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}
}