3

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?

shortspider
  • 957
  • 13
  • 29
  • No, you're not. Read about type erasure. – Martijn Courteaux Mar 31 '14 at 19:40
  • It will work if you do `new HashMap() { }`. Read about "super type tokens" to learn why. – Paul Bellora Mar 31 '14 at 19:59
  • @MartijnCourteaux is correct, you cannot get the types of the `HashMap`. What I ended up doing was looking at the `Class` of the key and value of an entry in the map. This does require an instance of the map instead of just the class but it works for me. Can I close this question or is it closed because it's marked as a duplicate? – shortspider Mar 31 '14 at 23:47

0 Answers0