工具类
使用范围:JavaBean类对象的属性不能是数组、List、Set、Map
public class MapBeanUtil {
/**
* JavaBean转Map
* @param obj
* @return
*/
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;
}
/**
* Map转JavaBean
* @param clazz
* @param map
* @param <T>
* @return
*/
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;
}