How do I address unchecked cast warnings?

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

    You can create a utility class like the following, and use it to suppress the unchecked warning.

    public class Objects {
    
        /**
         * Helps to avoid using {@code @SuppressWarnings({"unchecked"})} when casting to a generic type.
         */
        @SuppressWarnings({"unchecked"})
        public static  T uncheckedCast(Object obj) {
            return (T) obj;
        }
    }
    

    You can use it as follows:

    import static Objects.uncheckedCast;
    ...
    
    HashMap getItems(javax.servlet.http.HttpSession session) {
          return uncheckedCast(session.getAttribute("attributeKey"));
    }
    

    Some more discussion about this is here: http://cleveralias.blogs.com/thought_spearmints/2006/01/suppresswarning.html

提交回复
热议问题