Returned generic bounded type incorrect

35 views Asked by At

Hello I have a return type problem for a generic method that returns a subclass but the compiler thinks it returns the superclass, although I don't know why would that be a problem anyway.

  public <T extends SomeEntity> T createOrUpdateWithOwnerId(
      RepositoryContext repoCtx, T entity, String ownerId) throws SomeComponentException {
    return getEntityService(entity.getEntityType())
        .createOrUpdateWithOwnerId(repoCtx, entity, ownerId); //this doesn't compile 

Required: T, Provided: SomeEntity

  }

public class AuditableEntityService<T extends SomeEntity> {
  public T createOrUpdateWithOwnerId(RepositoryContext repoCtx, T entity, String ownerId)
      throws SomeComponentException {
    try {
      return persistenceRepository.saveOrUpdateWithOwnerId(repoCtx, entity, ownerId);
    } catch (RepositoryException e) {
      dealWithRepositoryException(entity, e);
      return null;
    }
  }
}

AuditableEntityService<AdminProfile> adminProfileService = new AuditableEntityService<>(new AdminProfile()); // where AdminProfile extends SomeEntity
1

There are 1 answers

0
Codrin Sirboiu On

I managed to fix it by adding another layer:

<T extends SomeEntity> AuditableEntityService<T> getEntityService(T entity)       throws SomeComponentException {
     return getEntityService(entity.getEntityType());   
} 

Where createOrUpdateWithOwnerId calls the new getEntityService(entity) so the type is the same as the parameter for sure.