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

Time:12-03

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

@Component
public class Mapper {
    private final ModelMapper modelMapper;

    @Autowired
    public Mapper(ModelMapper modelMapper) {
        this.modelMapper = modelMapper;
    }

    public Object convertToType(Object object, Class<?> type) {
        Object convertedObject = modelMapper.map(object, 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);

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

CodePudding user response:

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

public class Mapper {

    private final ModelMapper modelMapper;
    
    //ctor

    public <R> R convertToType(Object source, Class<R> resultClass) {
        return modelMapper.map(source, resultClass);
    }
}

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

  • Related