xybrek xybrek -4 years ago 54
Java Question

How to get the key and value type of a Map

I have this code that the app needs to do some check if the key of a

Map
given is
String
or not:

if(instance.getClass().equals(Map.class)){
Map map = (Map) instance;
if(keyIsString(map)){
// do stuff with the map
Iterator<Map.Entry> it = map.entrySet().iterator();
}
}


I can do it by getting the first item using the iterator and checking by
instanceof
however that would cause me to use two iterators. What is the best way to get the type of the Map key?

Update: I create a MapHelper class:

public class MapHelper {
public static String getKeyType(Map map){
String keyKind = Object.class.getName();
Iterator<Map.Entry<Object,Object>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Object,Object> entry = it.next();
Object entryKey = entry.getKey();
keyKind = entryKey.getClass().getName();
}
return keyKind;
}
public static String getValueType(Map map){
String valueKind = Object.class.getName();
Iterator<Map.Entry<Object,Object>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Object,Object> entry = it.next();
Object entryVal = entry.getValue();
valueKind = entryVal.getClass().getName();
}
return valueKind;
}
}


Is this good enough?

Answer Source

You cannot determine the type of a map at runtime. Because of type erasure they are no longer available.

From http://en.wikipedia.org/wiki/Generics_in_Java#Problems_with_type_erasure

Generics are checked at compile-time for type-correctness. The generic type information is then removed in a process called type erasure. For example, List<Integer> will be converted to the non-generic type List, which ordinarily contains arbitrary objects. The compile-time check guarantees that the resulting code is type-correct.

Consequent to type erasure, type parameters cannot be determined at run-time. For example, when an ArrayList is examined at runtime, there is no general way to determine whether, before type erasure, it was an ArrayList<Integer> or an ArrayList<Float>.

If you cannot make sure your compiler is already checking all types correctly, your only chance is fetching an element and assume all other elements are from the same type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download