我发现Java中的演员有些奇怪,我之前从未见过.在通用方法中编程时,实际上没有完成转换.
测试奇怪的事情.
在HashMap上:
HashMap<String,Object> map = ...
map.put("hello", "World");
System.err.println((Integer)map.get("hello")); // -----> ClassCastException
Run Code Online (Sandbox Code Playgroud)
在地图上包装
MapWrap wrap = ...
wrap.put("hello", "World");
System.err.println(wrap.get("hello",Integer.class)); // -----> don't cast, print World (i guess because println receives an Object reference but the cast should be done before that).
System.err.println(wrap.get("hello", Integer.class).toString()); // -----> print World + ClassCastException
Run Code Online (Sandbox Code Playgroud)
方法代码:
private <T> T get(String key, Class<T> c){
return (T)map.get(key);
}
private Object get(String key){
return map.get(key);
}
Run Code Online (Sandbox Code Playgroud)
有人知道mechansim是否有名字或者知道一些事情吗?
谢谢