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

前端 未结 3 1682
故里飘歌
故里飘歌 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

    Ultimately, because your map has Object as its value type, you need to cast, but you can hide this with a typed utility method:

    @SuppressWarnings("unchecked")
    public static  T get(Map map, String key) {
        return (T)map.get(key);
    }
    

    So then due to java's type inference this will compile:

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

    Adding @SuppressWarnings("unchecked") stops your IDE/compiler complaining about an "unsafe cast".

提交回复
热议问题