Map转Bean小工具

时间:2023-03-09 05:41:30
Map转Bean小工具
public static <T> T converter(Map<String, Object> map, Class<T> clz) {
T obj = null;
try {
obj = clz.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(clz);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (map.containsKey(key)) {
Object value = map.get(key);
// 得到property对应的setter方法
Method setter = property.getWriteMethod();
setter.invoke(obj, value);
}
}
} catch (Exception e) {
logger.error("map转{}异常", clz.getName(), e);
}
return obj;
}

  

public static <T> List<T> converter(List<Map<String, Object>> list, Class<T> clz) {
List<T> rst = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
rst.add(converter(list.get(i), clz));
}
return rst;
}