将所有 bean 属性复制到另一个 bean 的有效方法
Efficient way to copy all bean properties into another bean
我正在尝试将所有属性从一个 bean 复制到另一个:
public void copy(MyBean bean){
setPropertyA(bean.getPropertyA());
setPropertyB(bean.getPropertyB());
[..]
}
如果您有一个具有很多属性的 bean,这很容易出错并且要写很多东西。
我正在考虑反射来做到这一点,但我不能 "connect" 从一个对象的 getter 到另一个对象的 setter。
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);
工作正常!
考虑使用 Apache BeanUtils or Spring's BeanUtils。他们都有一个 copyProperties()
方法可以做你想做的事。
也可以想象JDK's Object.clone() will get you the results you need. Be sure to review the Javadoc and this SO post让你知道它的局限性。
如果您想手动执行此操作,我建议使用正在调用的 "Serialization copy"。一个限制是 bean 大多数实现 Serializable 接口。正如您所说,可以使用反射来完成,但您可能会遇到更多不便。
希望对您有所帮助。
我正在尝试将所有属性从一个 bean 复制到另一个:
public void copy(MyBean bean){
setPropertyA(bean.getPropertyA());
setPropertyB(bean.getPropertyB());
[..]
}
如果您有一个具有很多属性的 bean,这很容易出错并且要写很多东西。
我正在考虑反射来做到这一点,但我不能 "connect" 从一个对象的 getter 到另一个对象的 setter。
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);
工作正常!
考虑使用 Apache BeanUtils or Spring's BeanUtils。他们都有一个 copyProperties()
方法可以做你想做的事。
也可以想象JDK's Object.clone() will get you the results you need. Be sure to review the Javadoc and this SO post让你知道它的局限性。
如果您想手动执行此操作,我建议使用正在调用的 "Serialization copy"。一个限制是 bean 大多数实现 Serializable 接口。正如您所说,可以使用反射来完成,但您可能会遇到更多不便。 希望对您有所帮助。