1
class Super<T> {}

class Child<A, B> extends Super<B> {}

class Code {
  public void method(Child<String, Integer> child) {}
}

I can use reflection to get the parameter type:

ParameterizedType ptype = (ParameterizedType) Code.class.getMethod("method").getGenericParameterTypes()[0]

But how can I get the generic superclass of ptype (meaning, not only Super.class, but also the type parameter Integer)

My use case is that I want to use reflection to determine if one of the arguments of a method is a Collection of MyClass objects (I don't have an actual argument instance to check)

IttayD
  • 28,271
  • 28
  • 124
  • 178

3 Answers3

1

Type parameters are erased in java during compilation. Look here or there. So you probably will not able to do this.

Community
  • 1
  • 1
zvez
  • 818
  • 5
  • 8
  • if List extends Collection, and a parameter is of generic type List (that is, getRawType returns List.class and getActualTypeArguments returns [String.class]), then the JVM conceptually has all knowledge to know the parameter is also Collection. It is a matter of the reflection information, not type erasure (to know that the first generic parameter of List is also the first of Collection). But I guess there isn't one – IttayD Oct 23 '12 at 14:08
1

Well, from the example above you can do it. Because you can extract the actual type of the second type parameter (Integer) of the method parameter (Child).

Method method = Code.class.getMethod("method", Child.class);
ParameterizedType parameterType = (ParameterizedType) method.getGenericParameterTypes()[0];
Type secondType = parameterType.getActualTypeArguments()[1];
System.out.println(secondType == Integer.class);

Returns true.

sargue
  • 5,695
  • 3
  • 28
  • 43
0

As far as I understand you cannot do it.

You can extract type parameters of Child (String and Integer) using getActualTypeArguments(), but you cannot correlate them with T in Super<T>.

Also you can extract T from class Child extends Super<Integer>, but it's not your case.

It means that if you want to find Collection<MyClass> in arguments you can only do it if you have method(Collection<MyClass>), but not method(ArrayList<MyClass>) or something else.

axtavt
  • 239,438
  • 41
  • 511
  • 482