Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java Reflection Generic Type


How to get Java generic type parameter using reflection in runtime? Java doesn’t make it easy with type erasure, but it’s possible. See how.


In the following example we use reflection (java.lang.reflect package) in introspect content of sample class SampleClass and get return types of its public methods:


import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

public class ReflectGetGenericType {

    public static class SampleClass {

        public void returnsNothing() {
            System.out.println("Returns nothing");

        public String returnsString() {
            return "Hello reflection";

        public List<Integer> returnsListOfInts() {
            return Arrays.asList(1, 2, 3);

    public static void main(String[] args) {
        for (Method method : SampleClass.class.getDeclaredMethods()) {
            System.out.println("Method: " + method.getName());

    private static Class<?> getReturnType(Method method) {
        Type type = method.getGenericReturnType();
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            System.out.println("Return type: " + parameterizedType.getTypeName());
            type = parameterizedType.getActualTypeArguments()[0];
            System.out.println("Parameter type: " + type.getTypeName());
        } else {
            System.out.println("Return type: " + type);
        return (Class<?>) type;

We have to check if type is a ParametrizedType. It that’s the case we cast it appropriately and have access to its actual type arguments. In our case there’s only one argument, so we get the first element of the array.

Finally, non-parametrized types are instances of Class, so can be cast to it and passed to other tools that operate on class objects.

And here’s output of running the above example:

Method: returnsListOfInts
Return type: java.util.List<java.lang.Integer>
Parameter type: java.lang.Integer

Method: returnsNothing
Return type: void

Method: returnsString
Return type: class java.lang.String

As you can see, despite type erasure, we can get generic parameter type in runtime, having actual method object.

Share with the World!