MapStruct:对象类的映射

时间:2020-07-03 14:09:01

标签: java mapstruct

Class Source {
   private String type;
   private Object identifier;
}

标识符可以是 AppointmentIdentifier或JobIdentifier 类的对象; 我必须将Source映射到Target,其结构如下。

Class Target {
    private String type;
    private Object identifierBO;
}

identifierBO可以是 AppointmentIdentifierBO或JobIdentifierBO 类的对象。 下面是我的Mapper类:

@Mapper
public interface ModelMapper {

    Target toTarget(@NonNull final Source source);

    AppointmentIdentifierBO toAppointmentIdentifierBO(AppointmentIdentifier appointmentIdentifier);

    JobBO toJobBO(JobIdentifier jobIdentifier);
}

我知道,我缺少一些有助于将标识符映射到identifierBO的配置,但无济于事。

1 个答案:

答案 0 :(得分:2)

我只知道这种方法:

@Mapper
public interface ModelMapper {
    @Mapping(source = "identifier", target = "identifierBO", qualifiedByName = "identifierMapping")
    Target toTarget(Source source);

    @Named("identifierMapping")
    default Object mapIdentifier(Object obj) {
        if (obj instanceof AppointmentIdentifier)
            return toAppointmentIdentifierBO((AppointmentIdentifier) obj);

        if (obj instanceof JobIdentifier)
            return toJobBO((JobIdentifier) obj);

        throw new RuntimeException("Not supported type: " + obj.getClass());
    }

    AppointmentIdentifierBO toAppointmentIdentifierBO(AppointmentIdentifier appointmentIdentifier);

    JobBO toJobBO(JobIdentifier jobIdentifier);
}

太糟糕了?是。作品?是的。