How do you do THAT with generics  
Author Message
Barandis Alarion





PostPosted: 2005-3-8 0:53:00 Top

java-programmer, How do you do THAT with generics I am working on an event mechanism. Part of my need is to be able to
have a pool of events that can be reused, rather than incurring the cost
of instantiating one via reflection every time I need one. The pool
interface has this method for checking out an event:

<E extends Object & Event> E checkout(Class<E> cl);

Creating an event from this is easy; "return cl.newInstance();" works
fine. The problem is in storing them for later use.

Since there are many event classes in the event hierarchy, and since I
want this method to be able to return an event of the exact type (so I
don't have to cast it after getting it), I thought to use an inner class
(PoolList<E extends Event>) that holds a list of just one type of Event
and tracks which of its objects are in use and which are available. Then
I could use a Map to key these PoolList objects by Class.

That map is the problem. I need to have it store Class<E> as keys and
PoolList<E> as values...the same parameter (E) in both. Except that the
parameter isn't fixed...it could be any implementation of Event. So the
closest thing that I have is...

private Map<Class<? extends Event>, PoolList<? extends Event>> pool;

...which is wrong because it can't guarantee that the type parameters to
Class and to PoolList are the same (only that they are both
implementations of Event, but they could very well be different ones).
Something like...

private <T extends Event> Map<Class<T>, PoolList<T>> pool;

...would work, except that it isn't legal (the <T extends Event> part
can't be used for fields, only for generic methods). It makes sense that
there should be SOME way to do it...all of the necessary type
information is there at compile time and nothing that's needed at
runtime gets erased. But I can't come up with it.

All I need is a Map that knows that if one type parameter is being used
in the key, the same one should be used in the value. Is there a way in
generics to do this?