I’m trying to extend a library that uses generics in entities and entities manager, so I have the following:
public class MyEntity extends ParentEntity extends BaseEntity
and
public class MyEntityManager extends ParentEntityManager extends BaseEntityManager<ParentEntity, ParentEntityDao>
Now my problem is, I’m using another class of the library to update the entity, and the method I need to call expects:
public <ENT extends BaseEntity> void update (Class<ENT> entityClass, BaseEntityManager<ENT> entityManager)
So when I try to call the method with MyEntity and MyEntityManager, it fails because my EntityManager extends from the BaseEntityManager with ParentEntity as parameter, not MyEntity, so they don’t match.
I would say that the cleanest way to solve this would be to copy the utility class that has the update method and extend it in my project, but I would like to make it generic so I can pass it EntityManagers that use any children class of ParentEntity, but I’ve been trying for a while and I cannot find the solution.
I tried changing the method signature to this:
public <ENT extends BaseEntity> void update (Class<ENT> entityClass, BaseEntityManager<? extends ENT> entityManager)
but I’m still getting a compiler exception…
EDIT: Modifying ParentEntityManager, BaseEntityManager or ParentEntity is not possible, since there are too many dependencies to those classes
Since it doesn’t appear you can easily fix the problem I would use a work around. You can use type erasure.
This will compile with a warning. The warning is valid IMHO as your class structure isn’t entirely logical 😉 You can suppress this warning if you want.
What I do is; the container class returns the type of object it contains/manages.
The manager know what type it manages and the update() method can ask it by calling
typeManaged(). This avoid having to give a matching type or for this type to be checked.The problem you have is that
Which mean the class you have to provide is ParentEntity.class not MyEntity.class.
It appears the real solution is that you need to change
This would be more logical IMHO and fix your problem.