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

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

Description

get Generic Parameter

License

Mozilla Public License

Declaration

public static <T> Class<T> getGenericParameter(Class clazz, int index) 

Method Source Code

//package com.java2s;
//License from project: Mozilla Public License 

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

public class Main {
    public static <T> Class<T> getGenericParameter(Class clazz, int index) {
        Type genType = clazz.getGenericSuperclass();
        if (genType instanceof ParameterizedType) {
            return getGenericParameter((ParameterizedType) genType, index);
        }/*from w  w  w .  j  a  v  a 2s  .  c o  m*/
        return null;
    }

    public static <T> Class<T> getGenericParameter(Field field, int index) {
        Type genType = field.getGenericType();
        if (genType instanceof ParameterizedType) {
            return getGenericParameter((ParameterizedType) genType, index);
        }
        return null;
    }

    public static <T> Class<T> getGenericParameter(Method method, int index) {
        Type genType = method.getGenericReturnType();
        if (genType instanceof ParameterizedType) {
            return getGenericParameter((ParameterizedType) genType, index);
        }
        return null;
    }

    private static <T> Class<T> getGenericParameter(ParameterizedType type, int index) {
        Type param = type.getActualTypeArguments()[index];
        if (param instanceof Class) {
            return (Class) param;
        }
        return null;
    }
}

Related

  1. getGenericDeclaringType(Class baseClass, Class declaringClass)
  2. getGenericFirstClass(Type type)
  3. getGenericInterface(final Class sourceClass, final Class genericInterface)
  4. getGenericInterfaceParamType(Class cls, Class rawType)
  5. getGenericInterfacesActualTypes(Collection types, Class aClass)
  6. getGenericParameter(Type class1, int number)
  7. getGenericParameterClass(Class actualClass, int parameterIndex)
  8. getGenericParameterClass(Class clazz)
  9. getGenericParameters(Class clazz)