2

How do I get the actual type of T in a generic interface?

Given the following class:

class myClazz {
        private final IGenericInterface<?> genericInterface;

        myClazz(final IGenericInterface<otherClazz> genericInterface){
            this.genericInterface = genericInterface;
        }
}

How do I get the simple name of otherClazz out of the constructor using reflection?

I tried the following:

String otherClazzString = myClazz.class.getConstructors()[0].getParameterTypes()[0].toString(); // 

but I do not know what to do next to obtain the simple name of the actual type used in the generic interface.

Hadronymous
  • 566
  • 5
  • 16
  • Possible duplicate of [Get type of a generic parameter in Java with reflection](https://stackoverflow.com/questions/1901164/get-type-of-a-generic-parameter-in-java-with-reflection) – Dave Drake Jan 23 '18 at 19:04

1 Answers1

2

Close, but you need to use getGenericParameterTypes, as well as getDeclaredConstructors (since your constructor is not public):

Class<?> cls = (Class<?>) ((ParameterizedType) myClazz.class.getDeclaredConstructors()[0]
    .getGenericParameterTypes()[0]) // first constructor, first parameter
        .getActualTypeArguments()[0]; // first type argument

System.out.println(cls); // prints 'class otherClazz`

It should be noted that this code will only work if the type argument of the parameter is a concrete type, otherwise the cast to Class<?> will not work. For instance, in the case that the argument is a type variable, getActualTypeArguments()[0] will return an instance of TypeVariable instead of Class<...>.

Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93