找出 HashMap 中使用的类型
Finding out what type is being used in HashMap
我有一个从 JSON 文件填充的 HashMap。键值对中的值可以是两种不同的类型——字符串或另一个键值对。
例如:
HashMap<String,Object> hashMap = new Map();
JSON 文件看起来有点像这样:
"custom": {
"mappedReference": {"source": "someMappedReference"},
"somethingElse": "some literal"
}
}
稍后在填充 hashMap 之后,当我迭代时,我需要检查该值是 HashMap 类型还是 String 类型。我尝试了多种方法,但似乎无法获取 Map 中对象的类型。
for(Map.Entry<String,Object> m : hashMap.entrySet())
{
final String key = m.getKey();
final Object value = m.getValue();
if(value instanceof Map<String,String>)
{
//get key and value of the inner key-value pair...
}
else
{
//it's just a string and do what I need with a String.
}
}
关于如何从地图获取数据类型的任何想法?提前致谢
您可以像下面这样使用
ParameterizedType pt = (ParameterizedType)Generic.class.getDeclaredField("map").getGenericType();
for(Type type : pt.getActualTypeArguments()) {
System.out.println(type.toString());
参考:How to get value type of a map in Java?
我发布了一个类似问题的答案:
这里是:
通常不赞成不必要地使用 Object 类型。但是根据您的情况,您可能必须拥有一个 HashMap,尽管最好避免使用。也就是说,如果您必须使用一个,这里有一小段代码可能会有所帮助。它使用 instanceof.
Map<String, Object> map = new HashMap<String, Object>();
for (Map.Entry<String, Object> e : map.entrySet()) {
if (e.getValue() instanceof Integer) {
// Do Integer things
} else if (e.getValue() instanceof String) {
// Do String things
} else if (e.getValue() instanceof Long) {
// Do Long things
} else {
// Do other thing, probably want error or print statement
}
}
我有一个从 JSON 文件填充的 HashMap。键值对中的值可以是两种不同的类型——字符串或另一个键值对。
例如:
HashMap<String,Object> hashMap = new Map();
JSON 文件看起来有点像这样:
"custom": {
"mappedReference": {"source": "someMappedReference"},
"somethingElse": "some literal"
}
}
稍后在填充 hashMap 之后,当我迭代时,我需要检查该值是 HashMap 类型还是 String 类型。我尝试了多种方法,但似乎无法获取 Map 中对象的类型。
for(Map.Entry<String,Object> m : hashMap.entrySet())
{
final String key = m.getKey();
final Object value = m.getValue();
if(value instanceof Map<String,String>)
{
//get key and value of the inner key-value pair...
}
else
{
//it's just a string and do what I need with a String.
}
}
关于如何从地图获取数据类型的任何想法?提前致谢
您可以像下面这样使用
ParameterizedType pt = (ParameterizedType)Generic.class.getDeclaredField("map").getGenericType();
for(Type type : pt.getActualTypeArguments()) {
System.out.println(type.toString());
参考:How to get value type of a map in Java?
我发布了一个类似问题的答案:
这里是:
通常不赞成不必要地使用 Object 类型。但是根据您的情况,您可能必须拥有一个 HashMap,尽管最好避免使用。也就是说,如果您必须使用一个,这里有一小段代码可能会有所帮助。它使用 instanceof.
Map<String, Object> map = new HashMap<String, Object>();
for (Map.Entry<String, Object> e : map.entrySet()) {
if (e.getValue() instanceof Integer) {
// Do Integer things
} else if (e.getValue() instanceof String) {
// Do String things
} else if (e.getValue() instanceof Long) {
// Do Long things
} else {
// Do other thing, probably want error or print statement
}
}