将所有bean属性复制到另一个bean的有效方法

ker*_*000 2 java javabeans

我试图将所有属性从一个bean复制到另一个bean:

public void copy(MyBean bean){
    setPropertyA(bean.getPropertyA());
    setPropertyB(bean.getPropertyB());
    [..]
}
Run Code Online (Sandbox Code Playgroud)

如果你有一个具有大量属性的bean,这很容易出错并且需要编写很多东西.

我正在考虑反思这样做,但我不能将吸气剂从一个物体"连接"到另一个物体的设定者.

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

 BeanUtils.copyProperties(this, anotherBean);
Run Code Online (Sandbox Code Playgroud)

工作正常!

Stv*_*dll 5

考虑使用Apache BeanUtilsSpring的BeanUtils.他们都有一种copyProperties()方法可以做你想要的.

也可以想象JDK的Object.clone()将为您提供所需的结果.请务必查看Javadoc和此SO帖子,以便了解其局限性.