You can use the BeanWrapper
technology. Here's a sample implementation:
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)));
}
Or, if you really, really want to use BeanUtils
, here's a solution. Invert the logic, gather excludes by comparing the full property list with the includes:
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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…