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

时间:2015-03-17 21:19:15

标签: java spring

我正在尝试通过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>(); 
   ....
}

2 个答案:

答案 0 :(得分:0)

无法通过Bean Utils复制列表。您需要首先从DTO迭代电话号码列表然后进行最后的移动

答案 1 :(得分:0)

你可以用简单的旧反思来做到这一点。这将是一个深度适应列表。适应您的需求。

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);
            }
        }
    }