通过java的反射机制:
/**
* 对象转map
**/
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
if (obj == null) {
return null;
}
HashMap<String, Object> map = new HashMap<>();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
return map;
}
/**
* map转对象
**/
public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass) throws Exception {
if (map == null)
return null;
T obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
return obj;
}
/**
* Object转java实体类
**/
public static <T> T objectToEntity(Object obj, Class<T> beanClass) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
T result = objectMapper.convertValue(obj, beanClass);
return result;
}