Home > Java > javaTutorial > How to Get the Generic Type of a Java `List` Using Reflection?

How to Get the Generic Type of a Java `List` Using Reflection?

Patricia Arquette
Release: 2024-12-16 15:05:15
Original
294 people have browsed it

How to Get the Generic Type of a Java `List` Using Reflection?

How to Obtain Generic Type of java.util.List

Consider the following code:

List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();
Copy after login

A frequent question arises: is there an effortless method to retrieve the generic type of the list?

Using Reflection

If these lists are fields of a particular class, reflection can be utilized to access their generic types:

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

public class Test {

    List<String> stringList = new ArrayList<>();
    List<Integer> integerList = new ArrayList<>();

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

        Field stringListField = testClass.getDeclaredField("stringList");
        ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType();
        Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
        System.out.println(stringListClass); // class java.lang.String

        Field integerListField = testClass.getDeclaredField("integerList");
        ParameterizedType integerListType = (ParameterizedType) integerListField.getGenericType();
        Class<?> integerListClass = (Class<?>) integerListType.getActualTypeArguments()[0];
        System.out.println(integerListClass); // class java.lang.Integer
    }
}
Copy after login

Alternative Approaches

  • For parameter types and return types of methods, reflection can also be employed.
  • However, if the lists are within the same scope of the class/method that requires their generic types, knowing them is redundant, as they have already been explicitly declared.

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