Erasure error, while using generic types in methods with similar signature

Viewed 137

I want to have the following:

User UserDto UserMapper

userDto = userMapper.map(user);
user = userMapper.map(userDto);

My idea is to have a class similar to this:

public interface EntityMapper<E, D> {
    E map(D dto);
    D map(E entity);
}

but i am getting the following error:

'map(D)' clashes with 'map(E)'; both methods have same erasure

How can i achieve this without having 2 functions to map?

3 Answers

The problem is that both map(D dto) and map(E entity), essentially have the same signature. being map(Object dto) and map(Object entity). And there is no way for java to determine which method is being called when you call entityMapper.map(something); So, you need to define your method as follows:

public abstract class EntityMapper{
   public abstract <E extends AbstractEntity, D extends AbstractDto> E map(D dto);
   public abstract <E extends AbstractEntity, D extends AbstractDto> D map(E entity);
}

This should work, too:

public interface EntityMapper<D extends AbstractDTO, E extends AbstractEntity> {
    E map(D dto);
    D map(E entity);
}

This code may help you:

import org.mapstruct.*;
import org.springframework.stereotype.Component; 

@Component
@Mapper(componentModel = "spring", builder = @Builder(disableBuilder = true))
public abstract class EntityMapper{

    public abstract E map(D dto);
    public abstract D map(E entity);
 }
Related