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

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

Description

get Generic Class

License

Open Source License

Declaration

public static Class<?> getGenericClass(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 {
    public static Class<?> getGenericClass(Class clazz, int index) throws IllegalArgumentException {
        Type type = getGenericType(clazz, index);
        if (type instanceof Class<?>) {
            return (Class<?>) type;
        }/*from   w ww  . j a v a2  s .  c o  m*/
        throw new IllegalArgumentException("Generic parameter is not of type Class");
    }

    /**
     * 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. getGenericArgumentType(Class clazz)
  2. getGenericArgumentType(Class currentClass, Class genericSuperClass, int argumentIndex)
  3. getGenericClass(Class clazz)
  4. getGenericClass(Class clazz)
  5. getGenericClass(Class clazz)
  6. getGenericClass(Class clazz, int index)
  7. getGenericClass(Class clazz)
  8. getGenericClass(Class clazz, int index)
  9. getGenericClass(Class cls)