0

Suppose I have any given number of POJOs that all share common, identically named properties. Ideally I'd like to avoid a large interface with multiple mappers defined like

DtoA fromBToA(DtoB dtoB)
DtoB fromAToB(DtoA dtoA)
DtoC fromAToC(DtoA dtoA)

for each of the many POJOs I'll be dealing with.

Is it possible to define an interface which will accept any object and return any object? I tried

Object genericMapper(Object object)

This obviously doesn't work because it can't access the properties to generate the code.

I suppose since MapStruct documentation states:

This implementation uses plain Java method invocations for mapping between source and target objects, i.e. no reflection or similar.

what I'm requesting isn't possible, but I just thought I'd get closure or if there are any workarounds available.

Nanor
  • 2,400
  • 6
  • 35
  • 66
  • 1
    `Object genericMapper(Object object)` won't work because you'd have to at least define the target type you want to get. Also, mapstruct does a lot of compile-time magic so it will need to know which mappers to generate. – Thomas Apr 04 '23 at 10:51

1 Answers1

0

Unfortunately, it is not possible to use MapStruct for this.

So if for example you define a generic mapper like that:

@Mapper(componentModel = "spring")
public interface GenericMapper {

    <SOURCE, TARGET> TARGET toTarget(SOURCE source);
    
}

or like that:

@Mapper(componentModel = "spring")
public interface GenericMapper<SOURCE, TARGET> {

    TARGET toTarget(SOURCE source);
    
}

as soon as you try to build the project, you will get an error:

GenericMapper.java: Can't generate mapping method for a generic type variable source.

As an alternative solution, you can use BeanUtils.

see also: Copy all values from fields in one class to another through reflection

Paul Marcelin Bejan
  • 990
  • 2
  • 7
  • 14