Home >Java >javaTutorial >How to Get the Generic Type of a java.util.List using Reflection?

How to Get the Generic Type of a java.util.List using Reflection?

Linda Hamilton
Linda HamiltonOriginal
2024-12-22 21:26:171018browse

How to Get the Generic Type of a java.util.List using Reflection?

How to Obtain the Generic Type of a java.util.List

To retrieve the generic type of a given java.util.List, one can employ reflection techniques when the said list instances are fields within a class. Here's how it's done:

// Declare fields of type List<String> and List<Integer>
List<String> stringList = new ArrayList<>();
List<Integer> integerList = new ArrayList<>();

public static void main(String[] args) throws Exception {
    Class<Test> testClass = Test.class;

    // Obtain the Field object of the stringList field
    Field stringListField = testClass.getDeclaredField("stringList");
    // Determine the generic type of stringList using ParameterizedType
    ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType();
    // Retrieve the actual type argument (i.e., generic type) of stringListType
    Class<?> stringListClass = stringListType.getActualTypeArguments()[0];
    System.out.println(stringListClass); // class java.lang.String

    // Perform the same process for the integerList field
    Field integerListField = testClass.getDeclaredField("integerList");
    ParameterizedType integerListType = (ParameterizedType) integerListField.getGenericType();
    Class<?> integerListClass = integerListType.getActualTypeArguments()[0];
    System.out.println(integerListClass); // class java.lang.Integer
}

This approach is also applicable to parameter types and return types of methods. However, it's important to note that if the List instances are within the scope of the class or method where they're required, there's no need to use reflection as the generic types are explicitly declared.

The above is the detailed content of How to Get the Generic Type of a java.util.List using Reflection?. 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