简体   繁体   English

使用Dozer映射对象列表

[英]Mapping Lists of objects with Dozer

I created a dozer mapping for ClassA to ClassB. 我为ClassA创建了一个推土机映射到ClassB。

Now I want to map a List<ClassA> to a List<ClassB> . 现在我想将List<ClassA>映射到List<ClassB>

Is it possible to just 是否有可能

mapper.map(variableListClassA, variableListClassB) 

or do I have to go over a loop, eg 或者我必须经过一个循环,例如

for (ClassA classA : variableListClassA) {
    variableListClassB.add(mapper.map(classA, ClassB.class))
}

You need to use the loop, because the type of the list is erased at runtime. 您需要使用循环,因为列表的类型在运行时被擦除。

If both lists are a field of a class, you can map the owning classes. 如果两个列表都是类的字段,则可以映射拥有的类。

you could also use A helper class to do that in one step 您也可以使用辅助类一步完成

public class DozerHelper {

    public static <T, U> ArrayList<U> map(final Mapper mapper, final List<T> source, final Class<U> destType) {

        final ArrayList<U> dest = new ArrayList<U>();

        for (T element : source) {
        if (element == null) {
            continue;
        }
        dest.add(mapper.map(element, destType));
    }

    // finally remove all null values if any
    List s1 = new ArrayList();
    s1.add(null);
    dest.removeAll(s1);

    return dest;
}
}

and your call above would be like 而你上面的电话会是这样的

List<ClassB> listB = DozerHelper.map(mapper, variableListClassA, ClassB.class);

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

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