mapstruct 如何将对象列表转换为接口列表?

mapstruct How to convert a list of object to list of interface?

我有下面的界面和类

public interface Fruit { ... }

public class AppleDto implements Fruit {...}

public class AppleEntity { ... }

我创建了一个映射器,它将 AppleEntityList 转换为 AppleDtoList,但我需要 return 类型为 List Fruit.

@Mapper
public interface FruitsMapper {
    FruitsMapper INSTANCE = Mappers.getMapper(FruitsMapper.class);

    @IterableMapping(elementTargetType = AppleDto.class)
    List<Fruit> entityToFruits(List<AppleEntity> entity);
}

它不允许我转换为接口列表并给出错误。有什么合适的方法可以达到我的要求吗?

您需要在AppleEntityFruit之间定义一个映射方法,并通过@BeanMapping#resultType

定义结果类型

在你的情况下它看起来像:

@Mapper
public interface FruitsMapper {
    FruitsMapper INSTANCE = Mappers.getMapper(FruitsMapper.class);

    @BeanMapping(resultType = AppleDto.class)
    Fruit map(AppleEntity entity);

    List<Fruit> entityToFruits(List<AppleEntity> entity);
}

使用 @IterableMapping#elementTargetType 不是您所期望的。当有多种可能的映射方法时,它只是一个选择标准。来自它的 javadoc:

Specifies the type of the element to be used in the result of the mapping method in case multiple mapping
methods qualify.