I am trying to follow Joshua Bloch's typesafe hetereogeneous container pattern from Effective Java to create a container of objects (MyGeneric<T>
) with Class<T>
as a key.
public class MyClass {
private Map<Class<?>, MyGeneric<?>> myContainer =
new HashMap<Class<?>, MyGeneric<?>>();
public <T> void addToContainer(Class<T> class, MyGeneric<T> thing) {
myContainer.put(class, thing);
}
public <T> MyGeneric<T> getFromContainer(Class<T> class) {
return (MyGeneric<T>)(myContainer.get(klass));
}
}
The problem is in getFromContainer I have to perform a unchecked cast. In Josh Bloch's container, he performs a safe cast - but in my case I can't see a way how this is possible.
Does any one have any ideas?
Cheers, Nick.