我正在使用BeanUtils.copyProperties
转换两个bean。
BeanUtils.copyProperties(organization, dtoOrganization);
我想在一个bean中有一个
List
,在另一个bean中有一个Set
。第一粒豆:
public class Form {
private Set<Organization> organization;
}
第二粒豆:
public final class DTOForm {
private List<DTOOrganization> organization;
}
结果是一个异常,如下所示:
argument type mismatch by Using BeanUtils.copyProperties
是否可以自定义
BeanUtils.copyProperties
以实现它? 最佳答案
您可以使用自定义转换器解决它。主要思想是使用 Set
为ConvertUtils.register(Converter converter, Class<?> clazz)
注册新的转换器。实现您的自定义列表设置转换器的 convert(Class<T> type, Object value)
方法不是问题。
这是您的问题的简单示例:
ListEntity,它具有List
属性(据我所知,不要忽略setter和getter,它们的存在是必需的):
public class ListEntity {
private List<Integer> col = new ArrayList<>();
public List<Integer> getCol() {
return col;
}
public void setCol(List<Integer> col) {
this.col = col;
}
}
SetEntity,它具有
Set
属性:public class SetEntity {
private Set<Integer> col = new HashSet<>();
public Set<Integer> getCol() {
return col;
}
public void setCol(Set<Integer> col) {
this.col = col;
}
}
可以使用的简单测试类:
public class Test {
public static void main(String... args) throws InvocationTargetException, IllegalAccessException {
SetEntity se = new SetEntity();
se.getCol().add(1);
se.getCol().add(2);
ListEntity le = new ListEntity();
ConvertUtils.register(new Converter() {
@Override
public <T> T convert(Class<T> tClass, Object o) {
List list = new ArrayList<>();
Iterator it = ((Set)o).iterator();
while (it.hasNext()) {
list.add(it.next());
}
return (T)list;
}
}, List.class);
BeanUtils.copyProperties(le, se);
System.out.println(se.getCol().toString());
System.out.println(le.getCol().toString());
}
}
此代码截取器的主要思想是:我们为所有目标类
List
属性注册了Converter,它将尝试将某些对象o
转换为List
。假设o
是一个集合,我们对其进行迭代,然后返回新创建的列表。结果,
le
将同时包含1
和2
值。如果您不再需要此转换器,则可以使用 ConvertUtils.deregister()
取消注册。