tags:

views:

50

answers:

3

I have a method-

private void mapSomething(Class<?> dataType){

   if(dataType.isInstance(Map.class)){
      // How do I get the key set of the map
   }
}

Method is called like-

mapSomething(someHashMap.getClass()); // Hash Map

How do I get the key set of the map inside the method?

A: 

Have you tried

your_map.keySet()

?

CoolBeans
It's passing a Class. Do I really have to create a new instance of dataType?
Julian Soriano
Getting a key set is an instance operation. A class that implements Map does not have a key set associated with it. Each instance of that class has its own key set.
Dave Costa
Got it. Thanks Dave.
CoolBeans
+1  A: 

You can cast to a Map and retrieve the key set. If you want, you can also add unbounded generic parameter <?> to the map and set.

But you are only passing in the class of the data type. You also need to pass in the actual instance. E.g.

  mapSomething(someHashMap.getClass(), someHashMap)

And the implementation becomes:

  void mapSomething(Class<?> dataType, Object instance)
  {
       if(dataType.isInstance(Map.class)){
          Map<?,?> map = (Map<?,?>)instance;
          Set<?> keySet = map.keySet(); 
       }
  }

Altenatively, you can just pass the instance, and not the class

  void mapSomething(Object instance)
  {
       if(instance instanceof Map){
          Map<?,?> map = (Map<?,?>)instance;
          Set<?> keySet = map.keySet(); 
       }
  }
mdma
But there is a declaration of the map that is being passed. Can't we use the name (getName) of the dataType to use the map?
Julian Soriano
`getName` returns just what it's supposed to, the name of the class. No way to get back to the instance, once you passed in a class.
Willi
+5  A: 

You're not actually passing in an instance of Map (just its class data). If you can change your method signature to something like this it'd be easy enough:

private void mapSomething(Object data){
    if(data instanceof Map){
        ((Map)data).keySet()
    }
}
Mark E