如何从具有不同值类型的Map中获取值?(Java) [英] How to get values from a Map with different value types? (Java)
问题描述
我有一个实用函数,该函数返回 Map< String,Object>
,但是Map始终具有以下结构:
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> }
在外部函数中,我将其称为实用程序函数,我想获取与键 a
相关的值.我正在尝试执行以下操作:
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
我应该如何获取与键 a
相关的值?仅供参考:我是Java的新手.
How am I supposed to grab the value associated with key a
? FYI: I'm VERY new to Java.
推荐答案
您需要将从Map检索到的对象转换为所需的类型:
You need to cast the Object retrieved from Map to the type you required:
Type1 type1obj = (Type1) data.get("a");
但是在上面的代码中,您必须确保与键"a"关联的值的类型为Type1,否则将在运行时引发 ClassCastException
.
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
}
这篇关于如何从具有不同值类型的Map中获取值?(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!