Java Reflection Generic Type from Class getGenericType(Class clazz)

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

Description

get Generic Type

License

Apache License

Declaration

public static Class<?> getGenericType(Class<?> clazz) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    public static Class<?> getGenericType(Class<?> clazz) {

        return getGenericType(clazz, 0);
    }//from ww  w .  ja  v a  2  s. c om

    /**
     * Returns the generic type with the given index from the given {@link Class}.
     * Scan all base classes until finding a generic type.
     * 
     * @param clazz Class where seeking the generic type
     * @param index index of the generic type to find in the actual type array
     * @return the generic type
     */
    public static Class<?> getGenericType(Class<?> clazz, int index) {

        Type genericSuperclass = clazz.getGenericSuperclass();

        if (genericSuperclass == null) {
            return null;
        }

        Class<?> effectiveClass = clazz;
        while (!(genericSuperclass instanceof ParameterizedType)) {
            effectiveClass = effectiveClass.getSuperclass();
            genericSuperclass = effectiveClass.getGenericSuperclass();

            if (effectiveClass.equals(Object.class)) {
                return null;
            }
        }
        return (Class<?>) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[index];

    }
}

Related

  1. getGenericSuperType(Class clz, int index)
  2. getGenericSuperType(Class subclass, Class classWithParameter)
  3. getGenericSuperType(Class class1, Class class2)
  4. getGenericType(Class clazz, int index)
  5. getGenericType(Class propertyType)
  6. getGenericType(Class clazz)
  7. getGenericType(Class clazz, int index)
  8. getGenericType(Class target)
  9. getGenericType(Class type)