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

The identifier could be an object of class AppointmentIdentifier or JobIdentifier; I have to map Source to Target, which has below structure.

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

The identifierBO could an object of class AppointmentIdentifierBO or JobIdentifierBO. Below is my Mapper class:

@Mapper
public interface ModelMapper {

    Target toTarget(@NonNull final Source source);

    AppointmentIdentifierBO toAppointmentIdentifierBO(AppointmentIdentifier appointmentIdentifier);

    JobBO toJobBO(JobIdentifier jobIdentifier);
}

I know, I am missing some configuration which will help mapping identifier to identifierBO, but could not help.

1

1 Answers

2
votes

I only know this way to do this:

@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);
}

Horrible? Yes. Works? Yes.