Search code examples
javagenericsreflectionnested-generics

Getting class of parameter of super interface of superclass


I am having some troubles getting the parameter of an abstract superclass implementing a parametric interface.

I have these classes and interface:

interface Request<T extends Bean>

abstract class ProxyRequest<T extends Bean> implements Request<T>

class FooRequest extends ProxyRequest<Foo>

What I'm trying to achieve is to get Foo.class starting from a FooRequest instance.

I'm trying this but the result is T. What am I doing wrong?

FooRequest request = new FooRequest();
Type[] genericInterfaces = request.getClass().getSuperclass().getGenericInterfaces();
Type[] genericTypes = ((ParameterizedType)genericInterfaces[0]).getActualTypeArguments();
System.out.println(genericTypes[0]);

Solution

  • You're taking this one step too far. All you need is the generic super class (ProxyRequest<Foo>), which you can get by calling getGenericSuperclass, i.e.:

    FooRequest request = new FooRequest();
    Type[] genericTypes = ((ParameterizedType) request.getClass().getGenericSuperclass())
            .getActualTypeArguments();
    System.out.println(genericTypes[0]); // class Foo
    

    With your snippet you're getting T because:

    1. request.getClass() returns FooRequest.class
    2. .getSuperclass() returns ProxyRequest.class
    3. .getGenericInterfaces() returns an array with Request<T extends Bean>
    4. ((ParameterizedType)genericInterfaces[0]).getActualTypeArguments() returns an array with the TypeVariable<...> T, with Bean as a bound.