Example usage for java.lang Class getGenericSuperclass

List of usage examples for java.lang Class getGenericSuperclass

Introduction

In this page you can find the example usage for java.lang Class getGenericSuperclass.

Prototype

public Type getGenericSuperclass() 

Source Link

Document

Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class .

Usage

From source file:Main.java

/**
 * get generic class by actual type argument index.
 *//* w  w w  .j  a v  a 2s . co m*/
public static Class<?> getGenericClass(Class<?> cls, int actualTypeArgIndex) {
    try {
        ParameterizedType parameterizedType;
        if (cls.getGenericInterfaces().length > 0
                && cls.getGenericInterfaces()[0] instanceof ParameterizedType) {
            parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]);
        } else if (cls.getGenericSuperclass() instanceof ParameterizedType) {
            parameterizedType = (ParameterizedType) cls.getGenericSuperclass();
        } else {
            parameterizedType = null;
        }
        if (parameterizedType != null) {
            Object genericClass = parameterizedType.getActualTypeArguments()[actualTypeArgIndex];
            if (genericClass instanceof ParameterizedType) {
                return (Class<?>) ((ParameterizedType) genericClass).getRawType();
            } else if (genericClass instanceof GenericArrayType) {
                Class<?> componentType = (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType();
                if (componentType.isArray()) {
                    return componentType;
                } else {
                    return Array.newInstance(componentType, 0).getClass();
                }
            } else if (genericClass instanceof Class) {
                return (Class<?>) genericClass;
            }
        }
    } catch (Exception e) {
    }
    if (cls.getSuperclass() != null && cls.getSuperclass() != Object.class) {
        return getGenericClass(cls.getSuperclass(), actualTypeArgIndex);
    } else {
        throw new IllegalArgumentException(cls.getName() + " generic type undefined!");
    }
}

From source file:de.micromata.genome.util.runtime.ClassUtils.java

/**
 * Looks for the concreate Class of a generic of given classRequested.
 *
 * This implementation looks first in super classes and then in super interfaces.
 *
 * @param <T> the generic type//from   w  ww .j  a v  a  2 s  .c  o  m
 * @param clazz concrete class
 * @param classRequested class or interface implementing it.
 * @return null if not found.
 */
public static <T> Class<T> getGenericTypeArgument(Class<?> clazz, Class<T> classRequested) // NOSONAR "Methods should not be too complex" trivial
{
    Type genericSuperclass = clazz.getGenericSuperclass();
    if (genericSuperclass != null) {
        Class<T> ret = getGenericTypeArgumentFromGenericSuperType(genericSuperclass, classRequested);
        if (ret != null) {
            return ret;
        }
    }

    Type[] genericInterfaces = clazz.getGenericInterfaces();
    if (genericInterfaces == null) {
        return null;
    }
    for (Type genericInterface : genericInterfaces) {
        Class<T> ret = getGenericTypeArgumentFromGenericSuperType(genericInterface, classRequested);
        if (ret != null) {
            return ret;
        }
    }
    Class<?> superClazz = clazz.getSuperclass();
    if (superClazz != null) {
        return getGenericTypeArgument(superClazz, classRequested);
    }
    return null;
}

From source file:ReflectUtil.java

/**
 * Returns an array of Type objects representing the actual type arguments
 * to targetType used by clazz./*from  ww  w  . j a  v  a2s  .  c o  m*/
 * 
 * @param clazz the implementing class (or subclass)
 * @param targetType the implemented generic class or interface
 * @return an array of Type objects or null
 */
public static Type[] getActualTypeArguments(Class<?> clazz, Class<?> targetType) {
    Set<Class<?>> classes = new HashSet<Class<?>>();
    classes.add(clazz);

    if (targetType.isInterface())
        classes.addAll(getImplementedInterfaces(clazz));

    Class<?> superClass = clazz.getSuperclass();
    while (superClass != null) {
        classes.add(superClass);
        superClass = superClass.getSuperclass();
    }

    for (Class<?> search : classes) {
        for (Type type : (targetType.isInterface() ? search.getGenericInterfaces()
                : new Type[] { search.getGenericSuperclass() })) {
            if (type instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                if (targetType.equals(parameterizedType.getRawType()))
                    return parameterizedType.getActualTypeArguments();
            }
        }
    }

    return null;
}

From source file:com.smart.utils.ReflectionUtils.java

/**
 * ??,Class?.// www.ja v a 2  s  .  c o  m
 * 
 * public UserDao extends HibernateDao<User,Long>
 * 
 * @param clazz
 *            clazz The class to introspect
 * @param index
 *            the Index of the generic ddeclaration,start from 0.
 * @return the index generic declaration, or Object.class if cannot be
 *         determined
 */

@SuppressWarnings("unchecked")
public static Class getSuperClassGenricType(final Class clazz, final int index) {
    Type genType = clazz.getGenericSuperclass();
    if (!(genType instanceof ParameterizedType)) {
        logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
        return Object.class;
    }
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    if (index >= params.length || index < 0) {
        logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
                + params.length);
        return Object.class;
    }
    if (!(params[index] instanceof Class)) {
        logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
        return Object.class;
    }
    return (Class) params[index];
}

From source file:com.holonplatform.core.internal.utils.TypeUtils.java

/**
 * Return the type parameter of a generic type.
 * @param clazz subClass of <code>baseClass</code> to analyze.
 * @param baseClass base class having the type parameter the value of which we need to retrieve
 * @return the parameterized type value//ww w .  j  av a  2  s .  co m
 */
@SuppressWarnings("rawtypes")
public static Type getTypeArgument(Class<?> clazz, Class<?> baseClass) {
    Stack<Type> superclasses = new Stack<>();
    Type currentType;
    Class<?> currentClass = clazz;

    if (clazz.getGenericSuperclass() == Object.class) {
        currentType = clazz;
        superclasses.push(currentType);
    } else {

        do {
            currentType = currentClass.getGenericSuperclass();
            superclasses.push(currentType);
            if (currentType instanceof Class) {
                currentClass = (Class) currentType;
            } else if (currentType instanceof ParameterizedType) {
                currentClass = (Class) ((ParameterizedType) currentType).getRawType();
            }
        } while (!currentClass.equals(baseClass));

    }

    // find which one supplies type argument and return it
    TypeVariable tv = baseClass.getTypeParameters()[0];
    while (!superclasses.isEmpty()) {
        currentType = superclasses.pop();

        if (currentType instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) currentType;
            Class<?> rawType = (Class) pt.getRawType();
            int argIndex = Arrays.asList(rawType.getTypeParameters()).indexOf(tv);
            if (argIndex > -1) {
                Type typeArg = pt.getActualTypeArguments()[argIndex];
                if (typeArg instanceof TypeVariable) {
                    // type argument is another type variable - look for the value of that
                    // variable in subclasses
                    tv = (TypeVariable) typeArg;
                    continue;
                } else {
                    // found the value - return it
                    return typeArg;
                }
            }
        }

        // needed type argument not supplied - break and throw exception
        break;
    }
    throw new IllegalArgumentException(currentType + " does not specify a type parameter");
}

From source file:com.starlink.rest.util.Reflections.java

/**
 * ??, Class?./*from w  w  w  .  j a v  a  2  s  . c  o m*/
 * , Object.class.
 *
 * public UserDao extends HibernateDao<User,Long>
 *
 * @param clazz clazz The class to introspect
 * @param index the Index of the generic ddeclaration,start from 0.
 * @return the index generic declaration, or Object.class if cannot be determined
 */
public static Class getClassGenricType(final Class clazz, final int index) {

    // getGenericSuperclass()
    // Type Java ???????
    Type genType = clazz.getGenericSuperclass();

    // ParameterizedType??
    if (!(genType instanceof ParameterizedType)) {
        logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
        return Object.class;
    }

    // getActualTypeArguments???
    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

    if ((index >= params.length) || (index < 0)) {
        logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
                + params.length);
        return Object.class;
    }
    if (!(params[index] instanceof Class)) {
        logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
        return Object.class;
    }

    return (Class) params[index];
}

From source file:cc.sion.core.utils.Reflections.java

/**
 * ??/*from w ww.j  av a2  s .  c  o  m*/
 *
 * @param clazz
 * @param index
 * @param <T>
 * @return
 */
public static <T> Class<T> findParameterizedType(Class<?> clazz, int index) {
    //getSuperclass()
    //getGenericSuperclass()
    //Type Java ???????
    Type type = clazz.getGenericSuperclass();
    //CGLUB subclass target object()
    if (!(type instanceof ParameterizedType)) {
        type = clazz.getSuperclass().getGenericSuperclass();
    }
    if (!(type instanceof ParameterizedType)) {
        return null;
    }
    //ParameterizedType??
    ParameterizedType p = (ParameterizedType) type;
    //getActualTypeArguments???
    Type[] actualTypeArguments = p.getActualTypeArguments();
    if (actualTypeArguments == null || actualTypeArguments.length == 0) {
        return null;
    }
    return (Class<T>) actualTypeArguments[0];
}

From source file:GenericUtils.java

/**
 * Get the Generic definitions from a class for given class without looking
 * super classes./*from   w ww .j a va2  s.c  o  m*/
 * @param classFrom Implementing class
 * @param interfaceClz class with generic definition
 * @return null if not found
 */
@SuppressWarnings("unchecked")
public static Type[] getGenericDefinitonsThis(Class classFrom, Class interfaceClz) {

    Type[] genericInterfaces = classFrom.getGenericInterfaces();
    for (Type type : genericInterfaces) {
        if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) type;

            if (interfaceClz.isAssignableFrom((Class) pt.getRawType())) {
                return pt.getActualTypeArguments();
            }
        }

    }
    // check if it if available on generic super class
    Type genericSuperclass = classFrom.getGenericSuperclass();
    if (genericSuperclass instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) genericSuperclass;

        if (interfaceClz.equals(pt.getRawType())) {
            return pt.getActualTypeArguments();
        }
    }
    return null;

}

From source file:com.iterranux.droolsjbpmCore.internal.AbstractGenericFactory.java

/**
 * Get the actual type arguments a child class has used to extend a generic base class.
 *
 * @param baseClass the base class//from  www  .  j a va2s. co m
 * @param childClass the child class
 * @return a list of the raw classes for the actual type arguments.
 */
@SuppressWarnings("all")
public static <T> List<Class<?>> getTypeArguments(Class<T> baseClass, Class<? extends T> childClass) {

    Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
    Type type = childClass;
    // start walking up the inheritance hierarchy until we hit baseClass
    while (!getClass(type).equals(baseClass)) {
        if (type instanceof Class) {
            // there is no useful information for us in raw types, so just keep going.
            type = ((Class) type).getGenericSuperclass();
        } else {
            ParameterizedType parameterizedType = (ParameterizedType) type;

            Class<?> rawType = (Class) parameterizedType.getRawType();

            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
            for (int i = 0; i < actualTypeArguments.length; i++) {
                resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
            }

            if (!rawType.equals(baseClass)) {
                type = rawType.getGenericSuperclass();
            }
        }
    }

    // finally, for each actual type argument provided to baseClass, determine (if possible)
    // the raw class for that type argument.
    Type[] actualTypeArguments;
    if (type instanceof Class) {
        actualTypeArguments = ((Class) type).getTypeParameters();
    } else {
        actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
    }
    List<Class<?>> typeArgumentsAsClasses = new ArrayList<Class<?>>();
    // resolve types by chasing down type variables.
    for (Type baseType : actualTypeArguments) {
        while (resolvedTypes.containsKey(baseType)) {
            baseType = resolvedTypes.get(baseType);
        }
        typeArgumentsAsClasses.add(getClass(baseType));
    }
    return typeArgumentsAsClasses;
}

From source file:org.nerve.utils.reflection.ReflectionUtils.java

/**
 * ??, Class?./*from w  w w.ja  v  a2 s . c om*/
 * , Object.class.
 *
 * public UserDao extends HibernateDao?User,Long
 *
 * @param clazz clazz The class to introspect
 * @param index the Index of the generic ddeclaration,start from 0.
 * @return the index generic declaration, or Object.class if cannot be determined
 */
public static Class getClassGenricType(final Class clazz, final int index) {

    Type genType = clazz.getGenericSuperclass();

    if (!(genType instanceof ParameterizedType)) {
        System.err.println(clazz.getSimpleName() + "'s superclass not ParameterizedType");
        return Object.class;
    }

    Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

    if (index >= params.length || index < 0) {
        System.err.println("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
                + params.length);
        return Object.class;
    }
    if (!(params[index] instanceof Class)) {
        System.err.println(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
        return Object.class;
    }

    return (Class) params[index];
}