使用 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;
}
}