Home >Java >javaTutorial >Can Reflection Reveal Generic Parameter Types in Java?

Can Reflection Reveal Generic Parameter Types in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 11:27:11876browse

Can Reflection Reveal Generic Parameter Types in Java?

Retrieving Generic Parameter Types via Reflection in Java

Query: Can we ascertain the type of a generic parameter using reflection techniques?

Consider the following example:

public final class Voodoo {
    public static void chill(List<? extends SpiderMan> aListWithTypeSpiderMan) {
        // Obtain the Class object for 'SpiderMan'
        Class typeOfTheList = ???;
    }

    public static void main(String... args) {
        chill(new ArrayList<SpiderMan>());
    }
}

Solution:

A promising approach for extracting the generic parameter type is as follows:

Class<T> persistentClass = (Class<T>)
   ((ParameterizedType)getClass().getGenericSuperclass())
      .getActualTypeArguments()[0];

This rather arcane reflection-based incantation appears to furnish us with the desired result, but a more profound understanding of its intricacies eludes me for now.

The above is the detailed content of Can Reflection Reveal Generic Parameter Types in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn