1

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!

2 Answers 2

2

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>();
Sign up to request clarification or add additional context in comments.

Comments

2
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.

2 Comments

Although in this case you could have getTypeClass() return Class<Integer> or Integer.class. ;)
@Peter Yes. I just tried to show the process in generic way :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.