Get generic type for java.util.Map parameter

public Object[] convertTo(Map source, Object[] destination) {
    ...
}

Is it possible to define the common types (key / value) of my Map parameter through Reflection?

+5
source share
5 answers

Given Map<Key,Value>at run time it is not possible to determine Keyand Value. This is due to type erasure (also see Wikipedia ).

However, you can view each object (key or value) contained on the map and call their method getClass(). This will show you the execution type of this object. Note that this still says nothing about compilation type Keyand types Value.

+8
source

, , .
. :

private Map<String, Integer> genericTestMap = new HashMap<String, Integer>();

public static void main(String[] args) {

    try {

        Field testMap = Test.class.getDeclaredField("genericTestMap");
        testMap.setAccessible(true);

        ParameterizedType type = (ParameterizedType) testMap.getGenericType();

        Type key = type.getActualTypeArguments()[0];

        System.out.println("Key: " + key);

        Type value = type.getActualTypeArguments()[1];

        System.out.println("Value: " + value);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

:
Key: class java.lang.String
Value: class java.lang.Integer

+10

, getClass key/value . , , , / .

+1

, , , destination ( null.)

public <V> V[] convertTo(Map<?,V> source, V[] destination) {
    return source.values().toArray(destination);
}
+1

public class Demo 
{
    public static void main(String[] args) 
    {
        Map map = new HashMap<String, Long>();
        map.put("1$", new Long(10));
        map.put("2$", new Long(20));
        Set<?> set = map.entrySet();
        Iterator<?> iterator = set.iterator();
        String valueClassType="";
        while (iterator.hasNext()) 
        {
            Map.Entry entry = (Entry) iterator.next();
            valueClassType = entry.getValue().getClass().getSimpleName();
            System.out.println("key type : "+entry.getKey().getClass().getSimpleName());
            System.out.println("value type : "+valueClassType);
        }
    }
}
+1

All Articles