Object stringMap = new HashMap<String, String>(){{ put("1", "a"); }};
Map<Integer, String> integerMap = (Map<Integer, String>)stringMap; // Why doesn't Java throw an exception at run-time?
// I know this is not a problem if stringMap is declared as Map<String, String>.
// However, the actual code above was using Spring Bean.
// Map<Integer, String> integerMap = (Map<Integer, String>)context.getBean("map");
System.out.println(integerMap.get(1)); // prints null
System.out.println(integerMap.get("1")); // prints a
Q1. Why Java allows such casting at run-time?
Q2. If using bean, what is the best practice to avoid this error?
Q1. Because at run-time, all
genericinfo is already stripped away, so the twoMaptypes are indistinguishable for the run-time environment. Thegenericsare only there to help the compiler enforce type safety. To quote the Java Tutorials:Q2. Don’t use raw-typed Maps. If you have to, be really really careful when you typecast them.