实体对象和map的相互转换

在写增删改查,基本绕不过,对象与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);
    }

实体->map
    public static Map PojoToMap(Object object) throws Exception {
        Mapmap = new HashMap();
        Field[]fields = object.getClass().getDeclaredFields();//暴力反射获取所有字段
        for (Field field : fields){
            field.setAccessible(true);
            map.put(field.getName(),field.get(object));
        }
        return map;
    }
map->实体
    public static Object mapToPojo(Mapmap,Classpojo) throws Exception {
        Object object = pojo.newInstance();
        Field[]fields = object.getClass().getDeclaredFields();
        for (Field field:fields){
            int modifier = field.getModifiers();//返回此类或接口以整数编码的java语言修饰符。提供了静态方法和常量,可以对类和成员访问修饰符进行解码
            if (Modifier.isStatic(modifier)||Modifier.isFinal(modifier)){
                continue;
            }
            field.setAccessible(true);
            field.set(object,map.get(field.getName()));
        }
        return object;
    }

}

你可能感兴趣的:(java)