繁体   English   中英

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

[英]mapstruct How to convert a list of object to list of interface?

我有下面的接口和类

public interface Fruit { ... }

public class AppleDto implements Fruit {...}

public class AppleEntity { ... }

我创建了一个映射,它转换ListAppleEntityListAppleDto但我需要返回类型是ListFruit

@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.

暂无
暂无

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

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