【发布时间】:2012-07-09 17:18:47
【问题描述】:
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
第一季度。为什么 Java 允许在运行时进行这种类型转换?
第二季度。如果使用 bean,避免此错误的最佳做法是什么?
【问题讨论】: