Home > OS >  Abstraction of a ModelMapper
Abstraction of a ModelMapper

Time:07-10

I have an Entity-DTO converter for User like this:

public class UserConverter {
    
    public UserDto convertEntityToDto(UserEntity user) {
        ModelMapper modelMapper = new ModelMapper();
        return modelMapper.map(user, UserDto.class);
    }

    public UserEntity convertDtoToEntity(UserDto userDto) {
        ModelMapper modelMapper = new ModelMapper();
        return modelMapper.map(userDto, UserEntity.class);
    }

}

I have many Entity-DTO to manage, so I want to abstract the converter like this

public class Converter<T, S> {
    
    public S convertEntityToDto(T t) {
        ModelMapper modelMapper = new ModelMapper();
        return modelMapper.map(t, ???);
    }

    public T convertDtoToEntity(S s) {
        ModelMapper modelMapper = new ModelMapper();
        return modelMapper.map(s, ???);
    }

}

My problem is: what do I have to place instead of ???

CodePudding user response:

I think you can use TypeToken from modelMapper, but not sure will it work or not

CodePudding user response:

You'd expect that you can use S, right? Unfortunately (or fortunately?) the Java compiler erases all generic types before generating class files, so the code at runtime does not have the correct type information available. This means that you need to provide it instead.

public class Converter<T, S> {

    private Class<S> dtoType;

    public Converter(Class<S> dtoType) {
        this.dtoType = dtoType;
    }
    
    public S convertEntityToDto(T t) {
        ModelMapper modelMapper = new ModelMapper();
        return modelMapper.map(t, dtoType);
    }

    public T convertDtoToEntity(S s) {
        ModelMapper modelMapper = new ModelMapper();
        return modelMapper.map(s, dtoType);
    }

}
  • Related