java - 为什么 Java 不抱怨泛型映射转换?

Object stringMap = new HashMap(){{ put("1", "a"); }};

Map integerMap = (Map)stringMap; // Why doesn't Java throw an exception at run-time?

// I know this is not a problem if stringMap is declared as Map.

// However, the actual code above was using Spring Bean.

// Map integerMap = (Map)context.getBean("map");

System.out.println(integerMap.get(1)); // prints null

System.out.println(integerMap.get("1")); // prints a

Q1。为什么 Java 允许在运行时进行这种转换?

Q2。如果使用 bean,避免此错误的最佳做法是什么?

随便看看