使用 ModelMapper 映射抽象类型的字段

Using ModelMapper to map field of abstract type

我有以下 class 层次结构:

public abstract class Base {
    protected Boolean baseBoolean;
}
public class A extends Base {
    private BigDecimal amount;
}

并尝试将 DTO 映射到实体

public class DTO {
    private Base details;
}
public class Entity {
    private Base details;
}

并配图如下:

    public static void main(String[] args) {
        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setDeepCopyEnabled(true);

        A a = new A();
        a.setAmount(BigDecimal.ONE);
        a.setBaseBoolean(true);
        DTO request = DTO.builder().base(a).build();

        Entity entity = modelMapper.map(request, Entity.class);
        System.out.println(entity);
    }

我在详细信息字段中收到带有 A 或 B 的 DTO,这是用调试器检查的。但是模型映射器抛出

Failed to instantiate instance of destination org.package.Base. Ensure that org.package.Base has a non-private no-argument constructor.

我尝试使用显式提供程序(未用于此映射):

modelMapper.typeMap(A.class, Base.class).setProvider(new Provider<Base>() {
            @Override
            public Base get(ProvisionRequest<Base> r) {
                return new A();
            }
        });

我也试过像这样实现自定义转换器(也没有执行):

modelMapper.typeMap(A.class, Base.class).setConverter(new Converter<A, Base>() {
            @Override
            public Base convert(MappingContext<A, Base> mappingContext) {
               return modelMapper.map(mappingContext.getSource(), A.class);
            }
         });

modelmapper 似乎不将此类型映射用于字段,仅用于层次结构的根。 在这种情况下如何映射 class 层次结构?

如您所见,启用深层复制时会出现问题:modelMapper.getConfiguration().setDeepCopyEnabled(true)

一个解决方案是定义一个 Converter<Base, Base> 如下:

ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setDeepCopyEnabled(true); // this triggers the problem

// the converter resolves it
Converter<Base, Base> baseBaseConverter = context ->
        modelMapper.map(context.getSource(), context.getSource().getClass());

modelMapper.createTypeMap(Base.class, Base.class).setConverter(baseBaseConverter);

Live demo

Here 是关于该主题的更详细的 post。