参考示例之“复制对象|拷贝对象|BeanUtils工具类学习”

发布时间 2023-08-05 12:06:34作者: 骚哥
// 设置需要拷贝的字段   
Set<String> targetSet = new HashSet<>();
        targetSet.addAll(Arrays
                .asList("totalRefund", "actualAdvertisingCost", "expensesOfTaxation"));
// 调用拷贝方法
        copyProperties(combinationIncomeCosts.get(0), resultBeneficiary, targetSet);

 

将A对象的所有数据拷贝到B对象中

前提:保证两个对象的字段相同,B对象可以比A对象多字段

package org.springframework.beans;
BeanUtils.copyProperties(A, B);

 

 

将A对象的部分值数据拷贝到B对象中

这里可以调用方案,排除掉部分不需要的字段

import org.springframework.beans.BeanUtils;

BeanUtils.copyProperties(A, B, 排除的字段[可以数组,列表等]);

 

还可以优化,只要某些字段

// 设置需要拷贝的字段
Set<String> targetSet = new HashSet<>(); targetSet.addAll(Arrays.asList("totalRefund", "actualAdvertising", "expenses", "compensate"));
// 调用自定义拷贝方案 copyProperties(A
, B, targetSet);
  /**
     * 赋值指定字段值
     *
     * @param src
     * @param target
     * @param fieldSet
     */
    public static void copyProperties(Object src, Object target, Set<String> fieldSet)
    {
     // 过滤出所有不要的字段 String[] filteredPropertyNames
= Arrays.stream(BeanUtils.getPropertyDescriptors(src.getClass())) .map(PropertyDescriptor::getName).filter(e -> !fieldSet.contains(e)).toArray(String[]::new);
     // 实际上还是调用了排除的方案,将不要的字段加入到排除中 BeanUtils.copyProperties(src, target, filteredPropertyNames); }