Java general conversion, indirect

I find the actors in Java strange. I've never seen them before

Test strange things

On HashMap:

HashMap<String,Object> map = ...
map.put("hello","World");
System.err.println((Integer)map.get("hello")); //  -----> ClassCastException

Wrap on map

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

Method code:

private <T> T get(String key,Class<T> c){
    return (T)map.get(key);
}

private Object get(String key){
    return map.get(key);
}

Does anyone know if mechansim has a name or something about it?

thank you

Solution

Actors:

(T) map.get(key);

Because of type erasure, nothing is done at all MapWrap. The get () method will be deleted as:

private Object get(String key,Class<T> c){
    return map.get(key);
}

This will always work The cast of integer is inserted only where the result of this method is assigned to, and this does not happen because in the first mapwrap example, you passed it to a method that requires an object parameter

In the second case, you try calling integer Tostring() method, so the conversion inserted into integer will fail

You have passed in the class object. The correct way to perform "generic conversion" is as follows:

private <T> T get(String key,Class<T> c){
    return c.cast(map.get(key));
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>