Map与JavaBean之间相互转化

反射可以操作各种不同的Java类,而内省只是通过反射来操作JavaBean的。

FwoFk8.png

内省

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
public Map<String, Object> beanToMap(Object bean) {
Map<String, Object> map = new HashMap();

try {
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String key = propertyDescriptor.getName();
Object value = propertyDescriptor.getReadMethod().invoke(bean);
map.put(key, value);
}

} catch (Exception e) {
e.printStackTrace();
}

return map;
}

public <T> T mapToBean(Map<String, Object> map, Class<T> beanType) {
T bean = null;

try {
bean = beanType.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(beanType, Object.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String key = propertyDescriptor.getName();
Object value = map.get(key);
propertyDescriptor.getWriteMethod().invoke(bean, value);
}

} catch (Exception e) {
e.printStackTrace();
}

return bean;
}

反射

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
public Map<String, Object> beanToMap(Object bean) {
Map<String, Object> map = new HashMap();

try {
Class cls = bean.getClass();
Field[] fields = cls.getDeclaredFields();

for (Field field : fields) {
field.setAccessible(true);
String key = field.getName();
Object value = field.get(bean);
map.put(key, value);
}

} catch (Exception e) {
e.printStackTrace();
}

return map;
}

public <T> T mapToBean(Map<String, Object> map, Class<T> beanType) {
T bean = null;

try {
bean = beanType.newInstance();

for (String key : map.keySet()) {
Object value = map.get(key);
Field field = beanType.getDeclaredField(key);
field.setAccessible(true);
field.set(bean, value);
}

} catch (Exception e) {
e.printStackTrace();
}

return bean;
}