Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java Reflection Generic Type

farenda 2015-08-20 0

Problem:

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.

Solution:

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:

package com.farenda.java.lang.reflect;

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());
            getReturnType(method);
            System.out.println();
        }
    }

    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!
Categories Java Tags java-lang
Previous: Bash array
Next: Java reflection annotated fields/methods

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored