我正在使用 Spring 中的 BeanUtils 在同一类的两个对象之间复制属性。我想知道是否有一种方法可以在对其应用操作后将属性从源复制到目标。
假设所有属性都是整数。有没有办法“配置”BeanUtils,以便在调用 copyProperties 后目标对象将具有源对象值 + 1
?
最佳答案
没有。 BeanUtils有三个重载copyProperties(...)
方法,但它们只是从source
复制 bean 至target
bean 。
第一个将所有匹配的属性从源复制到目标。
copyProperties(Object source, Object target);
第二个仅复制在可编辑类或接口(interface)中指定的属性。
copyProperties(Object source, Object target, Class<?> editable)
第三个将所有属性从源复制到目标,指定的属性除外。
copyProperties(Object source, Object target, String... ignoreProperties)
如果您想做类似的事情,您必须创建自己的映射器类,执行 BeanUtils.copyProperties(...)
您想要的方法,然后浏览您想要执行的字段 +1
并再次设置它们。
类似
public class myMapper {
public Object map(final Object source) {
final Object target = new Object();
BeanUtils.copyProperties(source, target);
target.setProperty(target.getProperty() + 1);
// here modify and set all the properties you want.
return target;
}
}
关于java - Spring BeanUtils 、 copyProperties 和 apply 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60433525/