What I would like to have is something like this:
public abstract Class Content {
private Map<Class<? extends Content>, List<? extends Content>> relations;
}
Content has a bunch of subclasses – A,B,C,D etc…
The most frequent use case is to get all A’s:
public List<A> getA() {
return (List<A>)relations.get(A.class);
}
Kind of ok – apart from the ugly cast.
But the real problem is there’s nothing stopping me from doing something stupid like:
relations.put(A.class, List<B> myListOfBs);
So a call to getA() above would result in a horrible cast exception. Is there any way I can write it so the compiler would warn me in the above example – and also remove the need for the ugly cast.
Thanks
You can create a wrapper around a
Mapand use a generic method to constrain your put method:Now you know that as long as the users of the container aren’t using it improperly (i.e. in raw form) then the key and value must correspond…you couldn’t call
put(B.class, listOfAs);.