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

Can Reflection Reveal Generic Parameter Types in Java?

Mary-Kate Olsen
Release: 2024-12-22 11:27:11
Original
939 people have browsed it

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>());
    }
}
Copy after login

Solution:

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template