How do I address unchecked cast warnings?

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

    The obvious answer, of course, is not to do the unchecked cast.

    If it's absolutely necessary, then at least try to limit the scope of the @SuppressWarnings annotation. According to its Javadocs, it can go on local variables; this way, it doesn't even affect the entire method.

    Example:

    @SuppressWarnings("unchecked")
    Map myMap = (Map) deserializeMap();
    

    There is no way to determine whether the Map really should have the generic parameters . You must know beforehand what the parameters should be (or you'll find out when you get a ClassCastException). This is why the code generates a warning, because the compiler can't possibly know whether is safe.

提交回复
热议问题