An example where is does work:
class Favorites {
private Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
public <T> T get(Class<T> clazz) {
return clazz.cast(map.get(clazz));
}
public <T> void put(Class<T> clazz, T favorite) {
map.put(clazz, favorite);
}
}
which allows you to write:
Favorites favs = new Favorites();
favs.put(String.class, "Hello");
String favoriteString = favs.get(String.class);
The reason your code doesn't work is that Class.forName() returns a Class<?>
, i.e. a class object representing an unknown type. While the compiler could possibly infer the type in your example, it can not in general. Consider:
Class.forName(new BufferedReader(System.in).readLine())
what's the type of this expression? Clearly the compiler can not know what the class name will be at runtime, so it doesn't know whether
String s = Class.forName(new BufferedReader(System.in).readLine()).cast(o);
is safe. Therefore it requests an explicit cast.