[英]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: 我有一个实用函数,它返回
Map<String, Object>
,但Map始终具有以下结构:
{ "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
. 在外部函数中,我将其称为效用函数,我想获得与键
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
? 我应该如何获取与密钥
a
关联的值? FYI: I'm VERY new to Java. 仅供参考:我是Java的新手。
You need to cast the Object retrieved from Map to the type you required: 您需要将从Map检索到的对象转换为所需的类型:
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. 但是,使用上面的代码,您必须确保与键“ a”关联的值的类型为Type1,否则将在运行时引发
ClassCastException
。
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: 最终,由于地图将
Object
作为其值类型,因此需要进行转换,但是可以使用类型化的实用程序方法将其隐藏:
@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: 因此,由于java的类型推断,它将进行编译:
Type1 type1obj = get(data, "a");
Adding @SuppressWarnings("unchecked")
stops your IDE/compiler complaining about an "unsafe cast". 添加
@SuppressWarnings("unchecked")
阻止您的IDE /编译器抱怨“不安全的转换”。
Basically whenever I reach this point of storing with a HashMap or any map for that sort. 基本上,每当我达到使用HashMap或此类的任何地图进行存储的时候。 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.
例如,我有一个名为Module的类,该类正在获取其值,键是模块名。 I would go (Module) map.get(modName);
我去(模块)map.get(modName);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.