package com.ho.common.tools.util;

import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @Description 更新对象属性值
 * Author yule
 * Date 2023/1/6 10:00
 */
@Component
public class UpdateObjectUtil {

    /**
     * 把新对象的属性更新到老对象中(两个对象都属于同一个类)
     * @param oldObject
     * @param newObject
     * @return
     */
    public Object updateObjectAttribute(Object oldObject,Object newObject) {
        //获取该对象的属性字段
        Field[] fields = newObject.getClass().getDeclaredFields();
        //循环判断属性字段是否为空
        for (Field field : fields) {
            field.setAccessible(true);
                try {
                    Object o = field.get(newObject);
                    if (o != null) {
                        //将不为空的属性赋值到老对象中
                        field.set(oldObject, o);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        return oldObject;
    }
}
