我想所有屬性從一個豆複製到另一個:有效的方式,所有的bean的屬性複製到另一個豆
public void copy(MyBean bean){
setPropertyA(bean.getPropertyA());
setPropertyB(bean.getPropertyB());
[..]
}
這是容易出錯,如果你有一顆豆,有很多很多寫屬性。
我正在考慮反射來做到這一點,但是我不能將吸氣劑從一個物體「連接」到另一個物體的吸氣劑。
public List<Method> getAllGetters(Object object){
List<Method> result = new ArrayList<>();
for (final PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()) {
result.add(readMethod = propertyDescriptor.getReadMethod());
}
return result;
}
編輯:正如預期
BeanUtils.copyProperties(this, anotherBean);
作品!
而反射是錯誤的? – GurV
@GurwinderSingh,感謝您的寶貴意見。 – kerner1000
我在一些項目中使用了[Orika](http://orika-mapper.github.io/orika-docs/intro.html)和[Dozer](https://github.com/DozerMapper/dozer)。但是,我會去手動映射器。這並不困難,也不是那種容易出錯的。這些工具(Orika和Dozer)要麼需要配置,要麼使代碼依賴於任意的約定,雖然它們有幫助,但我認爲付出的代價非常高。 –