You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中Java对象非空属性覆盖复制实现方法

解决方案

首先先修正你提供的B类构造函数错误(类中仅定义了prop2和prop3,构造函数内的prop1、prop4属于无效引用),正确的B类构造函数应为:

public B(String prop2, String prop3) {
    this.prop2 = prop2;
    this.prop3 = prop3;
}

下面提供三种实现将B对象非空属性复制到A对象并覆盖对应属性的方案:

一、手动复制(简单直接,适合属性少的场景)

直接判断B对象的属性是否非空,非空则调用A对象的setter方法赋值,逻辑清晰且无额外依赖。

// 仅复制非空的prop2
if (b.getProp2() != null) {
    a.setProp2(b.getProp2());
}
// 仅复制非空的prop3
if (b.getProp3() != null) {
    a.setProp3(b.getProp3());
}

二、反射实现(通用型,适合属性多的场景)

通过反射遍历B类的所有属性,获取属性值后判断非空,再在A类中找到同名属性完成赋值,无需手动编写每个属性的判断逻辑。

import java.lang.reflect.Field;

public class ObjectCopyUtil {
    public static void copyNonNullProperties(Object source, Object target) throws IllegalAccessException {
        Class<?> sourceClazz = source.getClass();
        Class<?> targetClazz = target.getClass();

        // 遍历源对象(B)的所有属性
        Field[] sourceFields = sourceClazz.getDeclaredFields();
        for (Field sourceField : sourceFields) {
            sourceField.setAccessible(true);
            Object fieldValue = sourceField.get(source);
            
            // 仅处理非空属性
            if (fieldValue != null) {
                try {
                    // 查找目标对象(A)中的同名属性
                    Field targetField = targetClazz.getDeclaredField(sourceField.getName());
                    targetField.setAccessible(true);
                    targetField.set(target, fieldValue);
                } catch (NoSuchFieldException e) {
                    // 目标类无对应属性时直接跳过
                    continue;
                }
            }
        }
    }
}

使用方式:

try {
    ObjectCopyUtil.copyNonNullProperties(b, a);
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

三、基于Apache Commons BeanUtils实现(依赖第三方工具,减少重复代码)

原生BeanUtils会复制所有属性(包括null),因此需要自定义工具类过滤空值,需先引入依赖:

<!-- Maven依赖 -->
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

自定义非空属性复制工具:

import org.apache.commons.beanutils.BeanUtilsBean;

public class NonNullBeanUtils extends BeanUtilsBean {
    @Override
    public void copyProperty(Object dest, String name, Object value) throws IllegalAccessException, java.lang.reflect.InvocationTargetException {
        // 仅复制非空属性
        if (value != null) {
            super.copyProperty(dest, name, value);
        }
    }
}

使用方式:

NonNullBeanUtils nonNullBeanUtils = new NonNullBeanUtils();
try {
    nonNullBeanUtils.copyProperties(a, b);
} catch (Exception e) {
    e.printStackTrace();
}

内容的提问来源于stack exchange,提问作者Med

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 21:01:05