So long story short I have an object model in which several different entity types share a common supertype. Any type derived from this supertype has an owning User associated with it, and I want to provide a generic utility function that can return all the entities of a given type belonging to a specified User.
All of that works fine, but my function declaration looks like:
public static <T> List<T> findByUser(Class<T> entityClass, User user, EntityManager em)
…and although this is accepted by the compiler, the syntax looks a little strange to me. Is this the correct way to declare a function with a generic return type? Ideally what I’d like to have is something more like:
public static List<T> findByUser(Class<T extends MySuperClass> entityClass, User user, EntityManager em)
But the compiler doesn’t like that at all. So my specific questions are:
- Is there any way to get rid of the seemingly spurious
<T>element afterstatic? - What is the syntax that I need to use to make the compiler enforce that
Tmust be derived from my superclass type?
should work.
The
<T extends MySuperClass>is needed in the method signature (afterstatic) as that is where the bounds of the typeTare being defined.