I am learning Java and am currently reading Joshua Bloch's Effective Java.
In Item 29, he discusses parameterized type keys for Map to create a type-safe heterogeneous map. Here is the code:
class Favorites {
private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>();
public <T> void putFavorite(Class<T> type, T instance) {
if (type == null)
throw new NullPointerException("Type is null");
favorites.put(type, instance);
}
public <T> T getFavorite(Class<T> type) {
return type.cast(favorites.get(type));
}
}
He goes on to say that
A malicious client could easily corrupt the type safety of a Favorites instance, simply by using a Class object in its raw form. But the resulting client code would generate an unchecked warning when it was compiled.
I know that Class<T> would be erased to Class. But I am not sure how a malicious client can break the type safety at compile time. I tried various ways, but I always got a compiler error, as I expected.
Can someone please tell me what exactly Joshua Bloch meant in the line quoted above?