使用 BeanUtils.copyProperties 复制特定字段?

2022-09-01 03:05:41

springframework.beans.BeanUtils对于复制对象非常有用,我经常使用“忽略属性”选项。但是,有时我只想复制特定的对象(基本上,与“忽略属性”相反)。有谁知道我该怎么做?任何帮助将不胜感激。

import org.springframework.beans.BeanUtils;

public class Sample {    
    public static void main(String[] args) {    
        DemoADto demoADto = new DemoADto();
        demoADto.setName("Name of Demo A");
        demoADto.setAddress("Address of Demo A");

        DemoBDto demoBDto = new DemoBDto();

        // This is "ignoreProperties" option
        // But I want to know how I can copy only name field by using BeanUtils or something.
        BeanUtils.copyProperties(demoADto, demoBDto, new String[] {"address"});

        System.out.println(demoBDto.getName());
        System.out.println(demoBDto.getAddress());    
    }    
}

public class DemoADto {    
    private String name;    
    private String address;

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }    
}

public class DemoBDto {    
    private String name;    
    private String address;

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }    
}

答案 1

您可以使用 BeanWrapper 技术。下面是一个示例实现:

public static void copyProperties(Object src, Object trg, Iterable<String> props) {

    BeanWrapper srcWrap = PropertyAccessorFactory.forBeanPropertyAccess(src);
    BeanWrapper trgWrap = PropertyAccessorFactory.forBeanPropertyAccess(trg);

    props.forEach(p -> trgWrap.setPropertyValue(p, srcWrap.getPropertyValue(p)));

}

或者,如果你真的,真的想使用,这里有一个解决方案。反转逻辑,通过将完整属性列表与 include 进行比较来收集排除:BeanUtils

public static void copyProperties2(Object src, Object trg, Set<String> props) {
    String[] excludedProperties = 
            Arrays.stream(BeanUtils.getPropertyDescriptors(src.getClass()))
                  .map(PropertyDescriptor::getName)
                  .filter(name -> !props.contains(name))
                  .toArray(String[]::new);

    BeanUtils.copyProperties(src, trg, excludedProperties);
}

答案 2

如果你不想使用Commons BeanUtils,你仍然可以使用Spring,使用BeanWrapper

您必须手动遍历所有属性,因此您需要创建一个静态帮助器方法。

您可以随时复制copyProperties正在做的事情,并根据自己的喜好进行调整:http://tinyurl.com/BeanUtils-copyProperties


推荐