我正在使用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将同时包含12值。如果您不再需要此转换器,则可以使用 ConvertUtils.deregister() 取消注册。

10-07 19:24
查看更多