laprof :
I want to convert my entities to data access objects and I don't want to create a method for every entity. How can I convert my code into a generic method with generic return Entity
and param ObjectDTO
?
private ConcreteEntity convertToEntity(ConcreteObjectDTO objectDTO) throws ParseException {
ConcreteEntity entity = modelMapper.map(objectDTO, ConcreteEntity.class);
return entity;
}
I wrote the following code, but I don't know how to handle Entity.class
private <Entity, ObjectDTO> Entity convertToEntity(ObjectDTO objectDTO) throws ParseException {
Entity entity = modelMapper.map(objectDTO, Entity.class);
return entity;
}
John Kugelman :
Your method will need to take a Class
instance as a parameter so it can forward the right class to modelMapper.map()
. That means Class<E>
where E extends Entity
. Note that it's convention to give generic types single letter names.
Similarly, the ObjectDTO
should also be genericized as O extends ObjectDTO
or equivalent.
private <O extends ObjectDTO, E extends Entity> E convertToEntity(O objectDTO, Class<E> entityClass) throws ParseException {
return modelMapper.map(objectDTO, entityClass);
}
You may be able to skip genericizing the DTO parameter. It's probably not necessary.
private <E extends Entity> E convertToEntity(ObjectDTO objectDTO, Class<E> entityClass) throws ParseException {
return modelMapper.map(objectDTO, entityClass);
}