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

springframework.beans.BeanUtils复制对象非常有用,我经常使用“

ignoreProperties”选项。但是,有时我只想复制特定的对象(基本上是“忽略属性”的反义词)。有人知道我该怎么做吗?任何帮助将不胜感激。

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;

}

}

回答:

您可以使用该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)));

}

或者,如果你真的, 真的 想用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);

}

以上是 通过使用BeanUtils.copyProperties复制特定字段? 的全部内容, 来源链接: utcz.com/qa/436137.html

回到顶部