简体   繁体   中英

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

I have a utility function that returns Map<String, Object> , but that Map always has this structure:

{ "a": <something of type1>, "b": <something of type2> }

In outer function, where I call this utility function, I want to get the value associated with key a . I'm trying to do something such as:

Map<String, Object> data = findData(input); // findData is the utility function
Type1 type1obj = data.get("a"); // error here

But then I get the Incompatible Types error:

Required: com.blah.blah.Type1
Found: java.lang.Object

How am I supposed to grab the value associated with key a ? FYI: I'm VERY new to Java.

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
}

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> T get(Map<String, Object> 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".

Basically whenever I reach this point of storing with a HashMap or any map for that sort. I tend to go ahead and cast it. Take for example I have a class named Module that I am getting the value of and the key is the module name. I would go (Module) map.get(modName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM