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.
In Bloch's version, Class.cast()
is used - which is implemented as return (T) obj
, an unchecked cast. It's cheating in the sense that the compiler warning about unchecked cast is moved to a precompiled lib. The type safety of the cast is not guarded by compiler, but by app logic.
You shouldn't worry about unchecked cast either. There are type relations that cannot be expressed in the language, but which programmers know to be true. So just overrule the compiler, tell it the cast is safe.
Correction
My understanding about "unchecked cast" was incorrect.
Class.cast()
does not contain "unchecked cast". The cast is done after "checking", if the cast is reached at runtime, it's guaranteed to succeed.
T cast(Object obj)
if obj is instance of this class // check
return (T)obj; // cast
else
throw new ClassCastException
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With