How do I address unchecked cast warnings?

后端 未结 23 1217
醉梦人生
醉梦人生 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:53

    Almost every problem in Computer Science can be solved by adding a level of indirection*, or something.

    So introduce a non-generic object that is of a higher-level that a Map. With no context it isn't going to look very convincing, but anyway:

    public final class Items implements java.io.Serializable {
        private static final long serialVersionUID = 1L;
        private Map map;
        public Items(Map map) {
            this.map = New.immutableMap(map);
        }
        public Map getMap() {
            return map;
        }
        @Override public String toString() {
            return map.toString();
        }
    }
    
    public final class New {
        public static  Map immutableMap(
            Map original
        ) {
            // ... optimise as you wish...
            return Collections.unmodifiableMap(
                new HashMap(original)
            );
        }
    }
    
    static Map getItems(HttpSession session) {
        Items items = (Items)
            session.getAttribute("attributeKey");
        return items.getMap();
    }
    

    *Except too many levels of indirection.

提交回复
热议问题