在写增删改查,基本绕不过,对象与map的相互转换,掌握这几行代码,绝对帮助很大。
//调用两个转换方法之后最好做一下判空
public class FindThree {
public static void main(String[] args) throws Exception {
Student student = new Student();
student.setName("jack");
student.setSex("男");
Map map = (Map) FindThree.PojoToMap(student);//传入对象,返回map
System.out.println(map);
Student student1 = (Student) FindThree.mapToPojo(map,Student.class);//传入map,返回对象
System.out.println(student1);
}
public static Map<String,Object> PojoToMap(Object object) throws Exception {
Map<String , Object>map = new HashMap();
Field[]fields = object.getClass().getDeclaredFields();//暴力反射获取所有字段
for (Field field : fields){
field.setAccessible(true);
map.put(field.getName(),field.get(object));
}
return map;
}
public static Object mapToPojo(Map<String,Object>map,Class<?>pojo) throws Exception {
Object object = pojo.newInstance();
Field[]fields = object.getClass().getDeclaredFields();
for (Field field:fields){
int modifier = field.getModifiers();
if (Modifier.isStatic(modifier)||Modifier.isFinal(modifier)){
continue;
}
field.setAccessible(true);
field.set(object,map.get(field.getName()));
}
return object;
}
}









