1 添加maven 依赖
commons-beanutils commons-beanutils 1.9.32 使用
BeanUtils.populate(Map map, Object bean):将Map数据封装到JavaBean对象中
Map map = BeanUtils.describe(new DemoQueue()); 实体类转map
-
手动实现
public static T mapToEntity(Map<String,Object> map,Class beanClass) throws IllegalAccessException, InstantiationException {
if(map==null){ return null;}
Object obj =null;
obj = beanClass.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
int mod =0;
for (Field field : fields) {
mod = field.getModifiers();
if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
// 不设置静态 常量
continue;
}
field.setAccessible(true);
field.set(obj,map.get(field.getName()));
}
return (T)obj;
}public static Map<String,Object> entityToMap(Object object) throws IllegalAccessException {
if(object==null){ return null;}
Map map = new HashMap();
Field[]fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(),field.get(object));
}
return map;
}