mardi 7 janvier 2020

How to retrieve the class type via reflection of return object?

I want generalize some code but stuck on a problem which i think to be solved with reflection.

In my service methods I convert from dto to entity and vice versa. So I have in each service class a method like this

private LicenseDTO convertToDto(LicenseEntity entity) {
    LicenseDTO dto = modelMapper.map(entity, LicenseDTO.class);
    return dto;
}

To reduce duplication I moved this to an abstract class and there i want to genrealize this. S is my entity class an T my dto. The modelmapper requires the class type of S but how can I extract this via reflection?

    @SuppressWarnings("unchecked")
protected S convertToEntity(T dto){

    Class<S> typeOfS = null;
    typeOfS = (Class<S>) getClass();
    Method[] methods = typeOfS.getDeclaredMethods();


    return modelMapper.map(dto, typeOfS);
}




Aucun commentaire:

Enregistrer un commentaire