Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get generic type for java.util.Map parameter

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

Is there a possibility to figure out the generic types (key / value) of my Map parameter via Reflection?

like image 246
Sebi Avatar asked May 27 '11 06:05

Sebi


3 Answers

I know this question is old, but the best answer is wrong.
You can easily get the generic types via reflections. Here an example:

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();
    }
}

This will get you the output:
Key: class java.lang.String
Value: class java.lang.Integer

like image 98
Jofkos Avatar answered Nov 02 '22 22:11

Jofkos


Given a Map<Key,Value>, it isn't possible to figure out Key and Value at runtime. This is due to type erasure (also, see Wikipedia).

It is, however, possible to examine each object (key or value) contained in the map, and call their getClass() method. This will tell you the runtime type of that object. Note that this still won't tell you anything about the compile-type types Key and Value.

like image 38
NPE Avatar answered Nov 03 '22 00:11

NPE


You can inspect the Class for entries in the source object by getting each element, and calling getClass on the key/value object for each. Of course, if the map wasn't genericised at source then there's no guarantee that all the keys/values in it are of the same type.

like image 1
Joel Avatar answered Nov 03 '22 00:11

Joel