How do I address unchecked cast warnings?

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

    In the HTTP Session world you can't really avoid the cast, since the API is written that way (takes and returns only Object).

    With a little bit of work you can easily avoid the unchecked cast, 'though. This means that it will turn into a traditional cast giving a ClassCastException right there in the event of an error). An unchecked exception could turn into a CCE at any point later on instead of the point of the cast (that's the reason why it's a separate warning).

    Replace the HashMap with a dedicated class:

    import java.util.AbstractMap;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    public class Attributes extends AbstractMap {
        final Map content = new HashMap();
    
        @Override
        public Set> entrySet() {
            return content.entrySet();
        }
    
        @Override
        public Set keySet() {
            return content.keySet();
        }
    
        @Override
        public Collection values() {
            return content.values();
        }
    
        @Override
        public String put(final String key, final String value) {
            return content.put(key, value);
        }
    }
    

    Then cast to that class instead of Map and everything will be checked at the exact place where you write your code. No unexpected ClassCastExceptions later on.

提交回复
热议问题