I have an abstract class that takes a generic, in this class there's some methods.
My problem is that I can't use the generic E inside methods.
public abstract class AbstractRepository<E> implements Repository<E> {
final Class<E> typeParameterClass;
public AbstractRepository(Class<E> typeParameterClass) {
this.typeParameterClass = typeParameterClass;
}
...
@Override
public E findById(Integer id) {
try {
this.entityManager.find(typeParameterClass, id);
} catch (IllegalArgumentException error) {
error.printStackTrace();
} catch (PersistenceException error) {
error.printStackTrace();
}
return null;
}
I try to use generic E as parameter of 'find()' as below, but I got a error that says E is not defined.
@Override
public E findById(Integer id) {
try {
this.entityManager.find(E, id);
} catch (IllegalArgumentException error) {
error.printStackTrace();
} catch (PersistenceException error) {
error.printStackTrace();
}
return null;
}
To solve this I use typeParameterClass.
typeParameterClass is an argument that every other class that extends AbstractRepository have to pass, this argument is the class itself, but it does not seem right, since I already have the class in generic.
Example of the way how it is now:
@Repository
public class UserRepository extends AbstractRepository<User> {
public UserRepository(){
super(User.class);
}
...
}
So, is there a way to use generic E inside methods?
Repository is an interface that also takes the generic E.
I'm using Spring with Hibernate.