我想一个POJO对象的属性复制到另一个不可变对象的生成器,像这样:复制性能与春天
public class CopyTest {
// the source object
public static class Pojo1 {
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
// the target object
public static class Pojo2 {
private final int value;
public Pojo2(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static Pojo2Builder builder() {
return new Pojo2Builder();
}
// builder of the target object, maybe generated by lombok
public static class Pojo2Builder {
private int value;
private Pojo2Builder() {}
public Pojo2Builder value(int value) {
this.value = value;
return this;
}
public Pojo2 build() {
return new Pojo2(value);
}
}
}
public static void main(String[] args) {
Pojo1 src = new Pojo1();
src.setValue(1);
Pojo2.Pojo2Builder builder = Pojo2.builder();
// this won't work, provided by spring-beans
BeanUtils.copyProperties(src, builder);
Pojo2 target = builder.build();
}
}
的问题是: BeanUtils.copyProperties()
由spring-beans
提供不会拨打Pojo2Builder.value(int)
,因为它不是setter
;
除了生成器类通常是由lombok生成所以无法命名方法Pojo2Builder.value(int)
作为Pojo2Builder.setValue(int)
。
顺便说一句,我已经做了它使用注册一个定制的BeanIntrospector
由阿帕奇百科全书提供commons-beanutils
BeanUtilsBean.copyProperties()
,但我发现使用commons-beanutils
复制性能比使用spring-beans
当拷贝中的两个不同之间发生的贵得多类,所以我更喜欢做这个使用spring-beans
所以是有可能的属性复制到生成器类与Spring或其他一些公用事业这比commons-beanutils
更有效率?