简介
Map转换生成JavaBean是我们在实际项目开发中经常用到的功能,比如:在Servlet中,我们常通过request.getParameterMap()
获取前端页面传递过来的数据,然后再将其转换成对应的JavaBean。
待测试的JavaBean类
- Dept类
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class Dept {
/**
* 部门编号
*/
private Integer deptno;
/**
* 部门名称
*/
private String dname;
/**
* 部门地址
*/
private String loc;
}
- User
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class User {
private int id;
private String username;
private String email;
private boolean isAdmin;
private LocalDate birth;
private BigDecimal price;
private String[] array;
private List<String> list;
private Map<Integer, String> map;
private Dept dept;
}
方式一:自定义工具类
- 工具类
public class Map2JavaBeanUtil {
public static Object mapToObject(Map<String, Object> map, Class<?> clazz) throws Exception {
if (map == null) {
return null;
}
Object obj = clazz.getDeclaredConstructor().newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
Object o = map.get(property.getName());
if (o != null) {
setter.invoke(obj, o);
}
}
}
return obj;
}
}
- 测试代码
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("id", 1234);
map.put("username", "zhangsan");
map.put("email", "zhangsan@qq.com");
map.put("isAdmin", true);
map.put("birth", LocalDate.now());
map.put("price", new BigDecimal(22));
map.put("array", new String[]{"aa", "bb", "cc", "dd"});
map.put("list", List.of("11", "22", "33", "44"));
map.put("dept", new Dept(10, "sales", "chicago"));
map.put("map", Map.of("a", "aa", "b", "bb", "c", "cc"));
Object o = Map2JavaBeanUtil.mapToObject(map, User.class);
System.out.println(o);
}
- 结果
方式二:commons-beanutils
- Maven依赖
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
- 测试代码
public static void main(String[] args) throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("id", 1234);
map.put("username", "zhangsan");
map.put("email", "zhangsan@qq.com");
map.put("isAdmin", true);
map.put("birth", LocalDate.now());
map.put("price", new BigDecimal(22));
map.put("array", new String[]{"aa", "bb", "cc", "dd"});
map.put("list", List.of("11", "22", "33", "44"));
map.put("dept", new Dept(10, "sales", "chicago"));
map.put("map", Map.of("a", "aa", "b", "bb", "c", "cc"));
//Object o = Map2JavaBeanUtil.mapToObject(map, User.class);
//System.out.println(o);
User user = new User();
BeanUtils.populate(user, map);
System.out.println(user);
}
- 结果