How do I address unchecked cast warnings?

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

    Just typecheck it before you cast it.

    Object someObject = session.getAttribute("attributeKey");
    if(someObject instanceof HashMap)
    HashMap theHash = (HashMap)someObject;  
    

    And for anyone asking, it's quite common to receive objects where you aren't sure of the type. Plenty of legacy "SOA" implementations pass around various objects that you shouldn't always trust. (The horrors!)

    EDIT Changed the example code once to match the poster's updates, and following some comments I see that instanceof doesn't play nicely with generics. However changing the check to validate the outer object seems to play well with the commandline compiler. Revised example now posted.

提交回复
热议问题