java 使用 Dozer 映射对象列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14382939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:05:03  来源:igfitidea点击:

Mapping Lists of objects with Dozer

javamappingdozer

提问by user1323246

I created a dozer mapping for ClassA to ClassB.

我为 ClassA 到 ClassB 创建了一个推土机映射。

Now I want to map a List<ClassA>to a List<ClassB>.

现在我想将 a 映射List<ClassA>到 a List<ClassB>

Is it possible to just

是否有可能只是

mapper.map(variableListClassA, variableListClassB) 

or do I have to go over a loop, e.g.

还是我必须遍历一个循环,例如

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

采纳答案by artbristol

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.

如果两个列表都是类的字段,则可以映射所属类。

回答by MatthiasLaug

you could also use A helper class to do that in one step

您也可以使用 A helper 类一步完成此操作

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