How do I address unchecked cast warnings?

后端 未结 23 1711
醉梦人生
醉梦人生 2020-11-22 03:06

Eclipse is giving me a warning of the following form:

Type safety: Unchecked cast from Object to HashMap

This is from a call to

23条回答
  •  深忆病人
    2020-11-22 03:45

    In this particular case, I would not store Maps into the HttpSession directly, but instead an instance of my own class, which in turn contains a Map (an implementation detail of the class). Then you can be sure that the elements in the map are of the right type.

    But if you anyways want to check that the contents of the Map are of right type, you could use a code like this:

    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("a", 1);
        map.put("b", 2);
        Object obj = map;
    
        Map ok = safeCastMap(obj, String.class, Integer.class);
        Map error = safeCastMap(obj, String.class, String.class);
    }
    
    @SuppressWarnings({"unchecked"})
    public static  Map safeCastMap(Object map, Class keyType, Class valueType) {
        checkMap(map);
        checkMapContents(keyType, valueType, (Map) map);
        return (Map) map;
    }
    
    private static void checkMap(Object map) {
        checkType(Map.class, map);
    }
    
    private static  void checkMapContents(Class keyType, Class valueType, Map map) {
        for (Map.Entry entry : map.entrySet()) {
            checkType(keyType, entry.getKey());
            checkType(valueType, entry.getValue());
        }
    }
    
    private static  void checkType(Class expectedType, Object obj) {
        if (!expectedType.isInstance(obj)) {
            throw new IllegalArgumentException("Expected " + expectedType + " but was " + obj.getClass() + ": " + obj);
        }
    }
    

提交回复
热议问题