How do I address unchecked cast warnings?

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

    Unfortunately, there are no great options here. Remember, the goal of all of this is to preserve type safety. "Java Generics" offers a solution for dealing with non-genericized legacy libraries, and there is one in particular called the "empty loop technique" in section 8.2. Basically, make the unsafe cast, and suppress the warning. Then loop through the map like this:

    @SuppressWarnings("unchecked")
    Map map = getMap();
    for (String s : map.keySet());
    for (Number n : map.values());
    

    If an unexpected type is encountered, you will get a runtime ClassCastException, but at least it will happen close to the source of the problem.

提交回复
热议问题