下面就来分享工具类的内容:
使用范围:JavaBean
类对象的属性不能是数组、List
、Set
、Map
public class MapBeanUtil {
public static Map<String, Object> bean2Map(Object obj) {
Map<String, Object> map = new LinkedHashMap<>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = null;
try {
value = field.get(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if (value == null){
value = "";
}
map.put(fieldName, value);
}
return map;
}
public static <T> T map2Bean(final Class<T> clazz, final Map<String, ? extends Object> map) {
if (map == null) {
return null;
}
T res = null;
try {
res = clazz.getDeclaredConstructor().newInstance();
//获取到所有属性,不包括继承的属性
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
//获取字段的修饰符
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
//设置对象的访问权限
field.setAccessible(true);
//根据属性名称去map获取value
if(map.containsKey(field.getName())) {
//给对象赋值
field.set(res, map.get(field.getName()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
public static void main(String[] args) throws Exception {
HashMap<String, Object> map = new HashMap<>();
map.put("id", 1001);
map.put("username", "zhangsan");
map.put("password", "123456");
map.put("nickname", "张三");
map.put("email", "369950806@qq.com");
map.put("gender", true);
map.put("birth", LocalDate.now());
map.put("avatar", "/aa/bb/ab.jpg");
map.put("role", "VIP");
map.put("status", (byte) 1);
map.put("salt", "ldfkasjghweoiq324");
map.put("createTime", LocalDateTime.now());
map.put("updateTime", LocalDateTime.now());
User user = map2Bean(User.class, map);
System.out.println(user);
Map<String, Object> res = bean2Map(user);
System.out.println(map);
}
}
User类的代码:
public class User {
private Integer id;
private String username;
private String password;
private String nickname;
private String email;
private Boolean gender;
private LocalDate birth;
private String avatar;
private String role;
private Byte status;
private String salt;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
到此这篇关于Map与JavaBean相互转换的工具类 的文章就介绍到这了,更多相关Map与JavaBean相互转换内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!