Java Reflection Generic Type from Class getGenericType(Object o, Class declaringClass, int idx)

Here you can find the source of getGenericType(Object o, Class declaringClass, int idx)

Description

get Generic Type

License

Apache License

Return

the generic type class of a class.

Declaration

public static Class<?> getGenericType(Object o, Class<?> declaringClass, int idx) 

Method Source Code


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

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.LinkedList;

public class Main {
    /**//  w w w. j a  v a2 s.c  o  m
     * @return the generic type class of a class.
     */
    public static Class<?> getGenericType(Object o, Class<?> declaringClass, int idx) {
        Class<?> clazz = o.getClass();
        LinkedList<Class<?>> clazzStack = new LinkedList<Class<?>>();
        while (!clazz.getSuperclass().equals(declaringClass)) {
            clazzStack.push(clazz);
            clazz = clazz.getSuperclass();
        }

        while (clazz != null) {
            ParameterizedType ptype = (ParameterizedType) clazz.getGenericSuperclass();

            Type type = ptype.getActualTypeArguments()[idx];

            if (type instanceof Class<?>) {
                return (Class<?>) type;
            }

            TypeVariable<?> tvi = (TypeVariable<?>) type;
            TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
            for (idx = 0; idx < typeParameters.length; idx++) {
                TypeVariable<?> ctv = typeParameters[idx];
                if (ctv.getName().equals(tvi.getName())) {
                    break;
                }
            }
            clazz = clazzStack.pop();
        }

        return null;
    }
}

Related

  1. getGenericType(Class clazz)
  2. getGenericType(Class clazz, int index)
  3. getGenericType(Class target)
  4. getGenericType(Class type)
  5. getGenericType(Class type, Class clazz)
  6. getGenericType(Type type, Class rawType, int index)
  7. getGenericTypeArgument(Class clazz, int index)
  8. getGenericTypeArgumentFromGenericSuperType(Type genericSuperclass, Class baseRequested)
  9. getGenericTypeArgumentsOfInheritedType(final Object object, final Class inheritedType)