根据字段名 填充字段

时间:2021-09-06
本文章向大家介绍 根据字段名 填充字段,主要包括 根据字段名 填充字段使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
public class FullValue<D,T> {

    public static void main(String[] args) throws Exception {
        Student student = new Student();
        student.setId(UUID.randomUUID().toString());
        student.setName("张三");
        Teacher teacher = new Teacher();
        teacher = new FullValue<Student, Teacher>().full(student, teacher);
        System.out.println(teacher);
    }
    
    
    /**
     *
     * @param data       数据源
     * @param target     目标对象
     * @return
     * @throws Exception
     */
    public T full(D data,T target) throws Exception{
        Objects.requireNonNull(data);
        Objects.requireNonNull(target);
        for (Field targetField : target.getClass().getDeclaredFields()) {
            for (Field dataField : data.getClass().getDeclaredFields()) {
                if (Objects.equals(targetField.getName(),dataField.getName())){
                    targetField.setAccessible(true);
                    dataField.setAccessible(true);
                    targetField.set(target,dataField.get(data));
                    break;
                }
            }
        }
        return target;
    }

}


原文地址:https://www.cnblogs.com/immortal-mode/p/15234928.html