Type-safe mapping from Class<T> to Thing<T>
- by Joonas Pulakka
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?