Tom Tucker
Tom Tucker

Reputation: 11906

Accessing Type Parameters Using Reflection

How do I find type parameter values passed to a super class using reflection?

For example, given Bar.class, how do I find that it passes Integer.class to Foo's type parameter T?

public class Foo<T> {
}

public class Bar extends Foo<Integer> {
}

Thanks!

Upvotes: 1

Views: 386

Answers (2)

Puspendu Banerjee
Puspendu Banerjee

Reputation: 2651

public class Bar extends Foo<Integer> {

 public Class getTypeClass {
   ParameterizedType parameterizedType =
     (ParameterizedType) getClass().getGenericSuperClass();
  return (Class) parameterizedtype.getActualTypeArguments()[0];
 }

}

The given above should work in most of the practical situations,but not guaranteed, because of type erasure, there is no way to do this directly.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533510

You can try

ParameterizedType type = (ParameterizedType) Bar.class.getGenericSuperclass();
System.out.println(type.getRawType()); // prints; class Foo
Type[] actualTypeArguments = type.getActualTypeArguments();
System.out.println(actualTypeArguments[0]); // prints; class java.lang.Integer

This only works because Bar is a class which extends a specific Foo. If you declared a variable like the following, you wouldn't be able to determine the parameter type of intFoo at runtime.

Foo<Integer> intFoo = new Foo<Integer>();

Upvotes: 2

Related Questions