欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Map转实体类

程序员文章站 2022-06-15 11:22:39
...

项目中遇到过这样一个问题,sql查询出来的结果是一个Map<String,Object>,需要将map中对应的值放置到对应的实体类中,map中的key与实体类中的属性名一样。在属性值很少的时候,我们可以简单的取出值在set进实体类中,但是项目中一个类属性值可能有几十个,一个一个set的话会很麻烦,于是简答写一个转换的工具。

1.Model类

package com.boai.springboot2_learning.Model;

import java.time.LocalDate;
import java.time.LocalDateTime;

public class Student {

    private Integer id;
    private String name;
    private Integer age;
    private LocalDate birth;
    private LocalDateTime updateTime;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public LocalDate getBirth() {
        return birth;
    }

    public void setBirth(LocalDate birth) {
        this.birth = birth;
    }

    public LocalDateTime getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(LocalDateTime updateTime) {
        this.updateTime = updateTime;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("{");
        sb.append("\"id\":")
                .append(id);
        sb.append(",\"name\":\"")
                .append(name).append('\"');
        sb.append(",\"age\":")
                .append(age);
        sb.append(",\"birth\":")
                .append(birth);
        sb.append(",\"updateTime\":")
                .append(updateTime);
        sb.append('}');
        return sb.toString();
    }
}

2.反射方法类

package com.boai.springboot2_learning.Util;

import com.boai.springboot2_learning.Model.Student;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class ReflectUtil {

    public static Object getFidleValueFromObject(Object object, String fieldName) {
        Class<?> clazz = object.getClass();
        String getterName = String.format("get%c%s",
                Character.toUpperCase(fieldName.charAt(0)), fieldName.substring(1));
        System.out.println("方法名:" + getterName);
        Object value = null;
        try {
            Method method = clazz.getMethod(getterName);
            value = method.invoke(object, null);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return value;
    }

    private static String getSetterMethodName(String fieldName) {
        String setterName = String.format("set%c%s",
                Character.toUpperCase(fieldName.charAt(0)), fieldName.substring(1));
        return setterName;
    }

    public static void setObjectFieldValue(Object object, Object value, String fieldName) {
        Class<?> clazz = object.getClass();
        String methodName = getSetterMethodName(fieldName);
        Method method;
        try {
            if (value != null) {
                method = clazz.getMethod(methodName, value.getClass());
                method.invoke(object, value);
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static List<String> getFieldNames(Class clazz) {
        Field[] fields = clazz.getDeclaredFields();
        ArrayList<String> fieldNames = new ArrayList<>();
        Arrays.stream(fields).forEach(field -> fieldNames.add(field.getName()));
        return fieldNames;
    }

    public static void mapToObject(Object object, Map<String, Object> map) {
        Class<?> clazz = object.getClass();
        List<String> fieldNames = getFieldNames(clazz);
        fieldNames.stream().forEach(fieldName -> {
            Object o = map.get(fieldName);
            if (o != null) {
                if (o instanceof java.sql.Date) {
                    o = ((Date) o).toLocalDate();
                } else if (o instanceof Timestamp) {
                    o = ((Timestamp) o).toLocalDateTime();
                }
                setObjectFieldValue(object, o, fieldName);
            }
        });
    }

    public static void main(String[] args) {
        Student student = new Student();
        Map<String, Object> map = new HashMap<String, Object>() {
            {
                put("id", 123);
                put("name", "newName");
                put("age", 23);
                put("birth", LocalDate.now());
                put("updateTime", LocalDateTime.of(2019, 3, 30, 16, 9, 8));
            }
        };
        mapToObject(student, map);
        System.out.println(student.toString());
        System.out.println(student.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }
}

这里面只涉及到 部分值的类型转换,并没有写全部可能情况的类型转换,这里要根据实际情况进行处理;