【问题标题】:Finding out what type is being used in HashMap找出 HashMap 中使用的类型
【发布时间】:2017-02-14 13:44:13
【问题描述】:

我有一个从 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.
        }

    }

关于如何从地图中获取数据类型的任何想法?提前致谢

【问题讨论】:

标签: java json hashmap instanceof


【解决方案1】:

我发布了一个类似问题的答案:https://stackoverflow.com/a/42236388/7563898

这里是:

通常不赞成不必要地使用 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
    }
}

【讨论】:

  • 我休息了几天才回来工作。我打算为那些有想法发表评论的人发布答案。这正是我在上面自己的问题中弄清楚的。我会将此标记为答案。
【解决方案2】:

你可以像下面这样使用

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?

【讨论】:

  • 在这种情况下不可能:我们感兴趣的地图是从 Map 的值中获得的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-08
  • 2014-01-09
  • 2021-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多