Sic*_*ong 5 java generics casting map
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
Run Code Online (Sandbox Code Playgroud)
Q1.为什么Java允许在运行时进行这样的转换?
Q2.如果使用bean,避免此错误的最佳做法是什么?
| 归档时间: |
|
| 查看次数: |
537 次 |
| 最近记录: |