Java Reflection Generic Type from Class getGenericClass(Class clazz)

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

Description

get Generic Class

License

Open Source License

Declaration

public static Class getGenericClass(Class clazz) 

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) {
        return getGenericClass(clazz, 0);
    }/*  www .  ja v a 2s.co m*/

    public static Class getGenericClass(Class clazz, int index) throws IndexOutOfBoundsException {
        Type genType = clazz.getGenericSuperclass();

        while (!(genType instanceof ParameterizedType)) {
            if (clazz == Object.class) {
                return Object.class;
            }
            clazz = clazz.getSuperclass();
            genType = clazz.getGenericSuperclass();
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        if ((index >= params.length) || (index < 0)) {
            throw new IndexOutOfBoundsException(
                    "Index: " + index + ", Size of Parameterized Type: " + params.length);
        }
        return (Class) params[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, int index)
  6. getGenericClass(Class clazz, int index)
  7. getGenericClass(Class clazz)
  8. getGenericClass(Class clazz, int index)