Note that since Java uses type erasure, the implementation is actually of type
Map<?, ?> = Map<Object, Object>
You can trivially write a secure access method that gives you the necessary security by type and, for example, performs an instanceOf check:
public class InstanceMap extends HashMap<Class<?>, Object> { public <T> T getInstance(Class<T> cls) { Object o = super.get(cls); if (o != null && cls.isInstance(o)) { return (T) o; } else { return null; } } public <T> void putInstance(Class<T> cls, T value) { super.put(cls, value); } @Deprecated public Object get(Object key) { return super.get(key); } }
This will work just fine if you don't start using types that are universal in themselves. Class<? super T> Class<? super T> will help a little. But overall, it basically gives you a false sense of type safety. Such a card does not give you the reliable security you are used to. In the end, it's a little more than casting.
I used these cards before, but after using them for 1-2 years, I eventually pretty much removed them from my code during the cleanup phase. They were hacked and did not give me as many advantages as I expected from them.
source share