BeanUtils 实现 Map 与 Bean 进行相互转换

基本使用

Map -> Bean

1
BeanUtils.populate(Object bean, Map<String, ? extends Object> properties);

Bean -> Map

1
BeanMap testMap = new BeanMap(Object bean);

需要添加的 Maven 依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>

案例

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

public static void main(String[] args) throws Exception {
User user = new User();
Map<String, Object> map = new HashMap<>();
map.put("name", "Joe.Ye");
map.put("home", "http://www.appblog.cn");
map.put("city", "HZ");
map.put("age", 25);
BeanUtils.populate(user, map);
System.out.println(JSON.toJSONString(user));

BeanMap beanMap = new BeanMap(user);
System.out.println(JSON.toJSONString(beanMap));
}

public static class User {
String name;
String home;
int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getHome() {
return home;
}

public void setHome(String home) {
this.home = home;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}
}
1
2
{"age":25,"home":"http://www.appblog.cn","name":"Joe.Ye"}
{"name":"Joe.Ye","class":"com.lianlian.global.pay.test.MapBeanConvert$User","age":25,"home":"http://www.appblog.cn"}

功能封装

bean 转换成 map

1
2
3
4
5
6
7
8
9
10
11
12
13
private Map<String, String> bean2Map(Object object) {
Map<String, String> map = null;
try {
map = BeanUtils.describe(object);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}

private BeanMap bean2Map(Object object) {
return new BeanMap(object);
}

map 转换成 bean

1
2
3
4
5
6
7
8
9
10
private static <T> T map2Bean(Map<String, String> map, Class<T> clazz) {
T bean = null;
try {
bean = clazz.newInstance();
BeanUtils.populate(bean, map);
} catch (Exception e) {
e.printStackTrace();
}
return bean;
}