How do I address unchecked cast warnings?

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

    Wow; I think I figured out the answer to my own question. I'm just not sure it's worth it! :)

    The problem is the cast isn't checked. So, you have to check it yourself. You can't just check a parameterized type with instanceof, because the parameterized type information is unavailable at runtime, having been erased at compile time.

    But, you can perform a check on each and every item in the hash, with instanceof, and in doing so, you can construct a new hash that is type-safe. And you won't provoke any warnings.

    Thanks to mmyers and Esko Luontola, I've parameterized the code I originally wrote here, so it can be wrapped up in a utility class somewhere and used for any parameterized HashMap. If you want to understand it better and aren't very familiar with generics, I encourage viewing the edit history of this answer.

    public static  HashMap castHash(HashMap input,
                                                Class keyClass,
                                                Class valueClass) {
      HashMap output = new HashMap();
      if (input == null)
          return output;
      for (Object key: input.keySet().toArray()) {
        if ((key == null) || (keyClass.isAssignableFrom(key.getClass()))) {
            Object value = input.get(key);
            if ((value == null) || (valueClass.isAssignableFrom(value.getClass()))) {
                K k = keyClass.cast(key);
                V v = valueClass.cast(value);
                output.put(k, v);
            } else {
                throw new AssertionError(
                    "Cannot cast to HashMap<"+ keyClass.getSimpleName()
                    +", "+ valueClass.getSimpleName() +">"
                    +", value "+ value +" is not a "+ valueClass.getSimpleName()
                );
            }
        } else {
            throw new AssertionError(
                "Cannot cast to HashMap<"+ keyClass.getSimpleName()
                +", "+ valueClass.getSimpleName() +">"
                +", key "+ key +" is not a " + keyClass.getSimpleName()
            );
        }
      }
      return output;
    }
    

    That's a lot of work, possibly for very little reward... I'm not sure if I'll use it or not. I'd appreciate any comments as to whether people think it's worth it or not. Also, I'd appreciate improvement suggestions: is there something better I can do besides throw AssertionErrors? Is there something better I could throw? Should I make it a checked Exception?

提交回复
热议问题