繁体   English   中英

使用Beanutils复制包含列表的bean的属性

[英]Copy properties of bean containing list with Beanutils

我正在尝试通过Beanutils.copyproperties(Employee,EmployeeDTO)复制一个bean对象。 它在复制时不会引发任何异常,但是当我尝试检索EmployeeDTO.getPhoneNumber()它向我显示了ClassCastException,因为DTO对象显示了Employee对象的电话号码列表。

public class Employee implements Serializable {

   private String name;

   private String salary;

   private List<PhoneNumber> phoneNumber = new ArrayList<PhoneNumber>(); 

   ....
}

public class EmployeeDTO implements Serializable {

   private String name;

   private String salary;

   private List<PhoneNumber> phoneNumber = new ArrayList<PhoneNumber>(); 
   ....
}

列表不能通过Bean Utils复制。 您需要首先从DTO迭代电话号码列表以形成表格,然后进行最后一步

您可以使用简单的旧反射来完成此操作。 这将深入到一个容纳列表。 适应您的需求。

Method[] srcMethods = installation.getClass().getMethods();
    for (Method srcMethod : srcMethods) {
        if (srcMethod.getName().startsWith("get")) {
            try {
                String setMethodName = srcMethod.getName().replaceFirst("get", "set");
                Class<?> returnType = srcMethod.getReturnType();
                if(returnType.equals(java.util.List.class))
                    returnType = java.util.Collection.class;
                Method thisMethod = this.getClass().getMethod(setMethodName, returnType);
                log.info("attempting get and set on " + srcMethod.getName() + " " + thisMethod.getName());
                thisMethod.invoke(this, srcMethod.invoke(installation));
            } catch (Exception e) {
                log.error("SDK model out of sync with CM model", e);
            }
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM