Home > Java > javaTutorial > Can Java Reflection Retrieve Generic Parameter Types at Runtime?

Can Java Reflection Retrieve Generic Parameter Types at Runtime?

Susan Sarandon
Release: 2024-12-17 17:54:10
Original
579 people have browsed it

Can Java Reflection Retrieve Generic Parameter Types at Runtime?

Retrieving Generic Parameter Types via Java Reflection

In Java, developers may encounter the need to obtain the specific type of a generic parameter at runtime. This question explores how to achieve this common task using Java reflection.

Question:

Is it possible to retrieve the specific type of a generic parameter using Java reflection?

Scenario:

Consider the following code snippet:

public final class Voodoo {
    public static void chill(List<?> aListWithTypeSpiderMan) {
        // Here I'd like to get the Class-Object 'SpiderMan'
        Class typeOfTheList = ???;
    }

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

Answer:

Yes, obtaining the type of a generic parameter with reflection is possible. One approach involves utilizing the following code:

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

In this code, persistentClass will represent the actual type argument of the generic type, in this case, SpiderMan. However, it is important to note that the underlying reflection mechanisms can be complex, so a thorough understanding of Java generics and reflection is recommended for successful implementation.

The above is the detailed content of Can Java Reflection Retrieve Generic Parameter Types at Runtime?. 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