转换工具类常用于一些调用三方接口时候,要带一些额外的参数回调时候
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* 转换工具类
*/
public class ConvertUtil {
/**
* 实体类转map对象
*/
public static Map<String, Object> entityToMap(Object entity) {
Map<String, Object> map = new HashMap<>();
if (entity != null) {
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
map.put(field.getName(), field.get(entity));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
return map;
}
/**
* map转实体类
*/
public static <E> E mapToEntity(Map<String, Object> map, Class<E> clazz) {
E obj = null;
try {
obj = clazz.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
field.set(obj, map.get(field.getName()));
}
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
}