Java Reflection Generic Type from Class getGenericParameterType(Class clazz, Integer parameterIndex)

Here you can find the source of getGenericParameterType(Class clazz, Integer parameterIndex)

Description

note: for getting actual generic parameter, the object must be instantiated from an anonymouse class (in line class overriding)

License

Open Source License

Parameter

Parameter Description
T type of class which it's generic parameter type needs to be founded.
clazz a parameter
parameterIndex index2 of generic parameter. start from 0.

Return

generic type class. if not found, return null;

Declaration

public static <T> Class getGenericParameterType(Class<T> clazz, Integer parameterIndex) 

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 {
    /**/*from w  w  w . j a v a  2 s . c o m*/
     * note: for getting actual generic parameter, the object must be instantiated from an anonymouse
     * class (in line class overriding)
     *
     * @param <T> type of class which it's generic parameter type needs to be founded.
     * @param clazz
     * @param parameterIndex index2 of generic parameter. start from 0.
     * @return generic type class. if not found, return null;
     */
    public static <T> Class getGenericParameterType(Class<T> clazz, Integer parameterIndex) {
        Type type = clazz.getGenericSuperclass();
        if (!(type instanceof ParameterizedType))
            return null;
        ParameterizedType parameterizedType = ((ParameterizedType) clazz.getGenericSuperclass());
        Type[] types = parameterizedType.getActualTypeArguments();
        type = types[0];
        while (type instanceof ParameterizedType) {
            types = ((ParameterizedType) type).getActualTypeArguments();
            type = types[0];
        }
        if (parameterIndex >= types.length)
            throw new RuntimeException("" + "parameter index2(" + parameterIndex + ") is bigger than or equal to"
                    + " size of generic parameter lenght(" + types.length + ").");
        Class beanClass = (Class) types[parameterIndex];
        return beanClass;
    }

    public static <T> Class getGenericParameterType(Class<T> clazz, Integer parameterIndex, Class defaultClass) {
        Class typeClass = getGenericParameterType(clazz, parameterIndex);
        return typeClass != null ? typeClass : defaultClass;
    }
}

Related

  1. getGenericParameter(Class clazz, int index)
  2. getGenericParameter(Type class1, int number)
  3. getGenericParameterClass(Class actualClass, int parameterIndex)
  4. getGenericParameterClass(Class clazz)
  5. getGenericParameters(Class clazz)
  6. getGenericParameterType0(Class cls, Class genericSuper, int paramIndex)
  7. getGenerics(Class classType)
  8. getGenericsClass(Class cls)
  9. getGenericSuperclass(Class clazz)