How to create correctly a generic model mapper based on the code I wrote?


I am trying to create a generic model mapper using ModelMapper. This is what I got till now, it has only one method, that converts to the type given as second parameter

public class Mapper {
    private final ModelMapper modelMapper;

    public Mapper(ModelMapper modelMapper) {
        this.modelMapper = modelMapper;

    public Object convertToType(Object object, Class<?> type) {
        Object convertedObject =, type);
        return convertedObject;

And this is how I use it:
DepartmentDTO departmentDTO = (DepartmentDTO) modelMapper.convertToType(department.get(), DepartmentDTO.class);, here I convert from a department entity to it’s DTO class
And here I make the opposite, from DTO to entity.
Department department = (Department) modelMapper.convertToType(departmentDTO, Department.class);

How can I improve my code? Is it something wrong about the method I use?


If you want to avoid casting, use a generic method.

public class Mapper {

    private final ModelMapper modelMapper;

    public <R> R convertToType(Object source, Class<R> resultClass) {
        return, resultClass);

Additionally you can change method parameters names to something more descriptive of their functions – source and resultClass are just some possibilities.

Answered By – Chaosfire

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published