IttayD
IttayD

Reputation: 29163

get generic superclass of generic parameter

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)

Upvotes: 1

Views: 2439

Answers (3)

sargue
sargue

Reputation: 5915

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.

Upvotes: 1

axtavt
axtavt

Reputation: 242786

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.

Upvotes: 0

zvez
zvez

Reputation: 818

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

Upvotes: 1

Related Questions