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?
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
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With