在java中获取HashMap中的变量类型

RYN*_*RYN 4 java types hashmap

我有一个HashMap<String,Object>并存储了 3 种不同类型(整数、字符串、长整数)的一些数据。
如何找出具有特定键的值的类型?

SLa*_*aks 5

您可以调用该getClass方法来查找对象的类型:

map.get(key).getClass()
Run Code Online (Sandbox Code Playgroud)


小智 5

通常不赞成Object不必要地使用该类型。但根据您的情况,您可能必须使用HashMap<String, Object>,但最好避免使用。也就是说,如果您必须使用一个,这里有一小段代码可能会有所帮助。它使用 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
        }
    }
Run Code Online (Sandbox Code Playgroud)