如何将属性从一个Java bean复制到另一个?

pau*_*reg 14 java javabeans

我有一个简单的Java POJO,我将属性复制到同一个POJO类的另一个实例.

我知道我可以用BeanUtils.copyProperties()做到这一点,但我想避免使用第三方库.

那么,如何简单地,正确和安全的方式呢?

顺便说一下,我正在使用Java 6.

Dón*_*nal 12

我想如果你看一下BeanUtils的源代码,它会告诉你如何在不使用BeanUtils的情况下做到这一点.

如果您只是想创建POJO的副本(与将属性从一个POJO复制到另一个POJO不完全相同),您可以更改源bean以实现clone()方法和Cloneable接口.


Eft*_*mis 11

在为Google App Engine开发应用程序时遇到了同样的问题,由于公共日志限制,我无法使用BeanUtils.无论如何,我提出了这个解决方案,并为我工作得很好.

public static void copyProperties(Object fromObj, Object toObj) {
    Class<? extends Object> fromClass = fromObj.getClass();
    Class<? extends Object> toClass = toObj.getClass();

    try {
        BeanInfo fromBean = Introspector.getBeanInfo(fromClass);
        BeanInfo toBean = Introspector.getBeanInfo(toClass);

        PropertyDescriptor[] toPd = toBean.getPropertyDescriptors();
        List<PropertyDescriptor> fromPd = Arrays.asList(fromBean
                .getPropertyDescriptors());

        for (PropertyDescriptor propertyDescriptor : toPd) {
            propertyDescriptor.getDisplayName();
            PropertyDescriptor pd = fromPd.get(fromPd
                    .indexOf(propertyDescriptor));
            if (pd.getDisplayName().equals(
                    propertyDescriptor.getDisplayName())
                    && !pd.getDisplayName().equals("class")) {
                 if(propertyDescriptor.getWriteMethod() != null)                
                         propertyDescriptor.getWriteMethod().invoke(toObj, pd.getReadMethod().invoke(fromObj, null));
            }

        }
    } catch (IntrospectionException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)

任何增强或推荐都非常受欢迎.