我BeanUtils.copyProperties
用来转换两个bean。
BeanUtils.copyProperties(organization, dtoOrganization);
我想List
在一个豆子里放一个,在另一个豆子Set
里放一个。
第一个豆:
public class Form {
private Set<Organization> organization;
}
第二粒豆:
public final class DTOForm {
private List<DTOOrganization> organization;
}
结果是一个异常,如下所述:使用BeanUtils.copyProperties导致参数类型不匹配
是否可以定制BeanUtils.copyProperties
以达到目标?
您可以使用自定义转换器解决它。主要的想法是为注册新转换器Set
使用S 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()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句