Type-safe mapping from Class<T> to Thing<T>

Posted by Joonas Pulakka on Stack Overflow See other posts from Stack Overflow or by Joonas Pulakka
Published on 2010-06-09T06:28:47Z Indexed on 2010/06/09 6:32 UTC
Read the original article Hit count: 280

Filed under:
|
|
|

I want to make a map-kind of container that has the following interface:

public <T> Thing<T> get(Class<T> clazz);
public <T> void put(Class<T> clazz, Thing<T> thing);

The interesting point is that the Ts in each Class<T><-> Thing<T> pair is the same T, but the container should be able to hold many different types of pairs. Initially I tried a (Hash)Map. But, for instance,

Map<Class<T>, Thing<T>>

is not right, because then T would be same T for all pairs in that map. Of course,

Map<Class<?>, Thing<?>>

works, but then I don't have type-safety guarantees so that when I get(String.class), I can't be sure that I get a Thing<String> instance back.

Is there a way to accomplish the kind of type safety that I'm looking for?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics