mapstruct:使用 mapstruct 将对象数组转换为对象列表

mapstruct : Convert array of object to list of object using mapstruct

我有一个class

public class A {

Person[] getPersons() { .. }

}

public class B {

List<Person> getPersons() { .. }

}

我有将 A 转换为 B 的 Mapper,

@Mapper
public interface AMapper {
    AMapperINSTANCE = Mappers.getMapper(AMapper.class);

    B AtoB(A entity);

}

映射时,如何将人员数组转换为人员列表?

使用 java.util.Arrays 包中的静态方法 Array.asList(T...a)

示例:

class Person {
    private String name;

    Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}
@Test
public void arrayToList() {
    Person[] persons = {new Person("Yasuo"),new Person("Jinx")};

    List<Person> personList = Arrays.asList(persons);

    System.out.println(personList);
}

输出:

[Person{name='Yasuo'}, Person{name='Jinx'}]

MapStruct 自动创建用于在数组和 List 之间进行映射的中间方法。

您定义的内容:

public interface AMapper {
    AMapperINSTANCE = Mappers.getMapper(AMapper.class);

    B AtoB(A entity);

}

应该生成:

public class AMapperImpl implements AMapper {

    @Override
    public B AtoB(A entity) {
        if ( entity == null ) {
            return null;
        }

        B b = new B();

        b.setPersons( personArrayToPersonList( entity.getPersons() ) );

        return b;
    }

    protected List<Person> personArrayToPersonList(Person[] personArray) {
        if ( personArray == null ) {
            return null;
        }

        List<Person> list = new ArrayList<Person>( personArray.length );
        for ( Person person : personArray ) {
            list.add( person );
        }

        return list;
    }
}

说了这么多。您应该确保 类 中人员的 getters / setters 是 public。 MapStruct 是一个注释处理工具,它生成 java 代码并且不进行反射