JavaGenerics

Generics and Reflection

Reflection is the term for a set of features that allows a program to examine its own definition.

The central class for the Java reflection facility is Class<T> which is itself generic. It's worth spending the time to examine Class<T> methods that allow both examination of types and methods and instance creation.

There are number of methods and classes that can be used to examine generic objects definitions. Pay attention to the following:

Class<T>

Method

Type and its superinterfaces related to generics:


Let's illustrate the use of reflection to get generic type parameters with the following code:


// Generic interface
interface GenericInterface<T> {}

// Class that implements generic interface with some type argument
class SomeClass implements GenericInterface<Boolean> {}


// Let's get information on SomeClass type arguments
public class Main {
  public static void main(String[] args) {
    // Use getGenericInterfaces() method to retrieve list of SomeClass generic interfaces
    //    and provide them as Java 8 stream
    Stream.of(SomeClass.class.getGenericInterfaces())
        // Filter instances that are of ParameterizedType type and perform cast
        .filter(ParameterizedType.class::isInstance)
        .map(type -> (ParameterizedType) type)
        // Print type name
        .forEach(System.out::println);
  }
}


This code will print:

GenericInterface<java.lang.Boolean>

That perfectly corresponds with the fact that SomeClass implements GenericInterface parameterized with Boolean.

How did you like the theory?
Report a typo