How to copy properties from one Java bean to another?

前端 未结 8 1435
Happy的楠姐
Happy的楠姐 2020-12-17 15:53

I have a simple Java POJO that I would copy properties to another instance of same POJO class.

I know I can do that with BeanUtils.copyProperties() but I would like

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 16:03

    I had the same problem when developing an app for Google App Engine, where I couldn't use BeanUtils due to commons Logging restrictions. Anyway, I came up with this solution and worked just fine for me.

    public static void copyProperties(Object fromObj, Object toObj) {
        Class fromClass = fromObj.getClass();
        Class toClass = toObj.getClass();
    
        try {
            BeanInfo fromBean = Introspector.getBeanInfo(fromClass);
            BeanInfo toBean = Introspector.getBeanInfo(toClass);
    
            PropertyDescriptor[] toPd = toBean.getPropertyDescriptors();
            List 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();
        }
    }
    

    Any enhancements or recomendations are really welcome.

提交回复
热议问题