How to get values from a Map with different value types? (Java)

前端 未结 3 1577
故里飘歌
故里飘歌 2021-01-28 20:41

I have a utility function that returns Map, but that Map always has this structure:

{ \"a\": , \"b\"         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-28 21:15

    You need to cast the Object retrieved from Map to the type you required:

    Type1 type1obj = (Type1) data.get("a");
    

    But with the code above you have to make sure the type of value associated with key "a" is Type1, otherwise a ClassCastException will thrown at runtime.

    If you cannot guarantee the type of the Object retrieved, you can check it like:

    Object obj = data.get("a");
    Type1 type1obj;
    if(obj instanceof Type1) {
        type1obj = (Type1) obj;
    } else {
        //to print error log or do some workaround
    }
    

提交回复
热议问题