Java Reflection Generic Type from Class getGenericType(Class clazz, int index)

Here you can find the source of getGenericType(Class clazz, int index)

Description

Find the Generic Type of the form Class .

License

Open Source License

Parameter

Parameter Description
clazz Class
index Index of the Generic Type

Exception

Parameter Description
IllegalArgumentException when the Class does not have a Generic Type at the specified position or has none.

Return

Generic Type

Declaration

public static Type getGenericType(Class clazz, int index) throws IllegalArgumentException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class Main {
    /**/*  w  w  w  . j  a va 2  s .  co m*/
     * Find the Generic Type of the form {@code Class<GenericType>}.
     *
     * @param clazz Class
     * @param index Index of the Generic Type
     * @throws IllegalArgumentException when the Class does not have a Generic Type at the specified position or has none.
     * @return Generic Type
     */
    public static Type getGenericType(Class clazz, int index) throws IllegalArgumentException {
        ParameterizedType type = (ParameterizedType) clazz.getGenericSuperclass();
        if (type.getActualTypeArguments() == null || type.getActualTypeArguments().length <= index) {
            throw new IllegalArgumentException("No generic type at the specified position");
        }
        return type.getActualTypeArguments()[index];
    }
}

Related

  1. getGenericSuperclass(Class cls)
  2. getGenericSuperclassActualTypes(Collection types, Class aClass)
  3. getGenericSuperType(Class clz, int index)
  4. getGenericSuperType(Class subclass, Class classWithParameter)
  5. getGenericSuperType(Class class1, Class class2)
  6. getGenericType(Class propertyType)
  7. getGenericType(Class clazz)
  8. getGenericType(Class clazz)
  9. getGenericType(Class clazz, int index)