I am trying to get the type of the key and value of a HashMap
using reflection. I have the following code:
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
Class c = map.getClass();
if (c.getTypeParameters().length > 0) {
Type superClass = c.getGenericSuperclass();
TypeVariable<?> f = (TypeVariable<?>)(((ParameterizedType)superClass).getActualTypeArguments()[0]);
for (Type type1 : ((ParameterizedType)superClass).getActualTypeArguments()) {
TypeVariable<?> c1 = (TypeVariable<?>)type1;
System.out.println(c1.getBounds()[0]);
}
}
But this prints:
class java.lang.Object
class java.lang.Object
Instead of:
class java.lang.String
class java.lang.Integer
I assume I'm doing something stupid. Any ideas?