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:io.werval.runtime.util.TypeResolver.java

private static Map<TypeVariable<?>, Type> getTypeVariableMap(final Class<?> targetType) {
    Reference<Map<TypeVariable<?>, Type>> ref = CACHE.get(targetType);
    Map<TypeVariable<?>, Type> map = ref != null ? ref.get() : null;

    if (map == null) {
        map = new HashMap<>();

        // Populate interfaces
        buildTypeVariableMap(targetType.getGenericInterfaces(), map);

        // Populate super classes and interfaces
        Type genericType = targetType.getGenericSuperclass();
        Class<?> type = targetType.getSuperclass();
        while (type != null && !Object.class.equals(type)) {
            if (genericType instanceof ParameterizedType) {
                buildTypeVariableMap((ParameterizedType) genericType, map);
            }//from  w  ww .j  a v a2  s .c  o  m
            buildTypeVariableMap(type.getGenericInterfaces(), map);

            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }

        // Populate enclosing classes
        type = targetType;
        while (type.isMemberClass()) {
            genericType = type.getGenericSuperclass();
            if (genericType instanceof ParameterizedType) {
                buildTypeVariableMap((ParameterizedType) genericType, map);
            }

            type = type.getEnclosingClass();
        }

        if (cacheEnabled) {
            CACHE.put(targetType, new WeakReference<>(map));
        }
    }

    return map;
}

From source file:com.github.rvesse.airline.Accessor.java

private static Type[] getTypeParameters(Class<?> desiredType, Type type) {
    if (type instanceof Class) {
        Class<?> rawClass = (Class<?>) type;

        // if this is the collection class we're done
        if (desiredType.equals(type)) {
            return null;
        }// w w  w .j  av  a 2s .  com

        for (Type iface : rawClass.getGenericInterfaces()) {
            Type[] collectionType = getTypeParameters(desiredType, iface);
            if (collectionType != null) {
                return collectionType;
            }
        }

        return getTypeParameters(desiredType, rawClass.getGenericSuperclass());
    }
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;

        Type rawType = parameterizedType.getRawType();
        if (desiredType.equals(rawType)) {
            return parameterizedType.getActualTypeArguments();
        }

        Type[] collectionTypes = getTypeParameters(desiredType, rawType);
        if (collectionTypes != null) {
            for (int i = 0; i < collectionTypes.length; i++) {
                if (collectionTypes[i] instanceof TypeVariable) {
                    TypeVariable<?> typeVariable = (TypeVariable<?>) collectionTypes[i];
                    TypeVariable<?>[] rawTypeParams = ((Class<?>) rawType).getTypeParameters();
                    for (int j = 0; j < rawTypeParams.length; j++) {
                        if (typeVariable.getName().equals(rawTypeParams[j].getName())) {
                            collectionTypes[i] = parameterizedType.getActualTypeArguments()[j];
                        }
                    }
                }
            }
        }
        return collectionTypes;
    }
    return null;
}

From source file:com.yx.baseframe.util.ReflectionUtils.java

/**
 * Get the actual type arguments a child class has used to extend a generic
 * base class. (Taken from http://www.artima.com/weblogs/viewpost.jsp?thread=208860. Thanks
 * mathieu.grenonville for finding this solution!)
 * /*  ww  w.j  av a2s  .  c om*/
 * @param baseClass
 *            the base class
 * @param childClass
 *            the child class
 * @return a list of the raw classes for the actual type arguments.
 */
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:com.frame.base.utils.ReflectionUtils.java

/**
 * Get the actual type arguments a child class has used to extend a generic
 * base class. (Taken from http://www.artima.com/weblogs/viewpost.jsp?thread=208860. Thanks
 * mathieu.grenonville for finding this solution!)
 * //from  w  w w .  j a va 2  s  .c  o m
 * @param baseClass
 *            the base class
 * @param childClass
 *            the child class
 * @return a list of the raw classes for the actual type arguments.
 */
@SuppressWarnings("rawtypes")
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.kurento.test.base.BrowserTest.java

public static Class<?> getParamType(Class<?> testClass) {

    Type genericSuperclass = testClass.getGenericSuperclass();

    if (genericSuperclass != null) {

        if (genericSuperclass instanceof Class) {
            return getParamType((Class<?>) genericSuperclass);
        }/*from  w w  w .  jav a  2 s .  c  om*/

        ParameterizedType paramClass = (ParameterizedType) genericSuperclass;

        return (Class<?>) paramClass.getActualTypeArguments()[0];
    }

    throw new RuntimeException("Unable to obtain the type paramter of KurentoTest");
}

From source file:com.github.dactiv.common.utils.ReflectionUtils.java

/**
 * ??, Class?. , Object.class.??/*from   ww w  .j  av a2 s .  c o m*/
 * 
 * <pre>
 * 
 * public UserDao extends HibernateDao<User,Long>
 * </pre>
 * 
 * @param targetClass
 *            ???Class
 * @param index
 *            ?????
 * 
 * @return class
 */
public static Class getSuperClassGenricType(final Class targetClass, final int index) {

    Assert.notNull(targetClass, "targetClass?");

    Type genType = targetClass.getGenericSuperclass();

    if (!(genType instanceof ParameterizedType)) {
        logger.warn(targetClass.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 " + targetClass.getSimpleName() + "'s Parameterized Type: "
                + params.length);
        return Object.class;
    }
    if (!(params[index] instanceof Class)) {
        logger.warn(targetClass.getSimpleName()
                + " not set the actual Class targetClassn superclass generic parameter");
        return Object.class;
    }

    return (Class) params[index];
}

From source file:com.jaspersoft.jasperserver.war.helper.GenericParametersHelper.java

public static Class<?> getGenericTypeArgument(Class<?> classToParse, Class<?> genericClassToFind,
        Integer argumentIndex) {/*from  ww w.  j  a  v  a2s.  c o  m*/
    Class<?> result = null;
    ParameterizedType parameterizedType = null;
    Class<?> currentClass = classToParse;
    Map<String, Class<?>> currentParameterValues = new HashMap<String, Class<?>>();
    Type[] previousTypeArguments = null;
    while (parameterizedType == null) {
        final TypeVariable<? extends Class<?>>[] typeParameters = currentClass.getTypeParameters();
        currentParameterValues = getCurrentParameterValues(typeParameters, previousTypeArguments,
                currentParameterValues);
        parameterizedType = findParametrizedType(currentClass, genericClassToFind, currentParameterValues);
        if (parameterizedType == null) {
            // current class doesn't extend/implement searched class directly. Should parse superclass
            final Type genericSuperclassType = currentClass.getGenericSuperclass();
            if (genericSuperclassType instanceof Class<?>) {
                log.debug(classToParse.getName() + " is raw subclass of " + genericClassToFind.getName());
                return null;
            }
            final ParameterizedType genericSuperclass = (ParameterizedType) genericSuperclassType;
            previousTypeArguments = genericSuperclass.getActualTypeArguments();
            currentClass = (Class<?>) genericSuperclass.getRawType();
        }
    }
    final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    if (actualTypeArguments[argumentIndex] instanceof Class<?>) {
        result = (Class<?>) actualTypeArguments[argumentIndex];
    } else if (actualTypeArguments[argumentIndex] instanceof TypeVariable) {
        result = currentParameterValues.get(((TypeVariable<?>) actualTypeArguments[argumentIndex]).getName());
    }
    if (result == null) {
        log.debug("Class " + classToParse.getName() + " has unsupported inheritance structure");
    }
    return result;
}

From source file:antre.TypeResolver.java

/**
 * Resolves the generic Type for the {@code targetType} by walking the type hierarchy upwards from
 * the {@code initialType}.//ww w  . jav  a 2  s  .c  o m
 */
public static Type resolveGenericType(Type initialType, Class<?> targetType) {
    Class<?> rawType;
    if (initialType instanceof ParameterizedType)
        rawType = (Class<?>) ((ParameterizedType) initialType).getRawType();
    else
        rawType = (Class<?>) initialType;

    if (targetType.equals(rawType))
        return initialType;

    Type result;
    if (targetType.isInterface()) {
        for (Type superInterface : rawType.getGenericInterfaces())
            if (superInterface != null && !superInterface.equals(Object.class))
                if ((result = resolveGenericType(superInterface, targetType)) != null)
                    return result;
    }

    Type superType = rawType.getGenericSuperclass();
    if (superType != null && !superType.equals(Object.class))
        if ((result = resolveGenericType(superType, targetType)) != null)
            return result;

    return null;
}

From source file:org.springframework.core.GenericTypeResolver.java

/**
 * Build a mapping of {@link TypeVariable#getName TypeVariable names} to
 * {@link Class concrete classes} for the specified {@link Class}. Searches
 * all super types, enclosing types and interfaces.
 *///from  w w w  .j a va2s .  co  m
public static Map<TypeVariable, Type> getTypeVariableMap(Class clazz) {
    Map<TypeVariable, Type> ref = typeVariableCache.get(clazz);
    Map<TypeVariable, Type> typeVariableMap = (ref != null ? ref : null);

    if (typeVariableMap == null) {
        typeVariableMap = new HashMap<TypeVariable, Type>();

        // interfaces
        extractTypeVariablesFromGenericInterfaces(clazz.getGenericInterfaces(), typeVariableMap);

        // super class
        Type genericType = clazz.getGenericSuperclass();
        Class type = clazz.getSuperclass();
        while (type != null && !Object.class.equals(type)) {
            if (genericType instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) genericType;
                populateTypeMapFromParameterizedType(pt, typeVariableMap);
            }
            extractTypeVariablesFromGenericInterfaces(type.getGenericInterfaces(), typeVariableMap);
            genericType = type.getGenericSuperclass();
            type = type.getSuperclass();
        }

        // enclosing class
        type = clazz;
        while (type.isMemberClass()) {
            genericType = type.getGenericSuperclass();
            if (genericType instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) genericType;
                populateTypeMapFromParameterizedType(pt, typeVariableMap);
            }
            type = type.getEnclosingClass();
        }

        typeVariableCache.put(clazz, typeVariableMap);
    }

    return typeVariableMap;
}

From source file:org.vulpe.commons.util.VulpeReflectUtil.java

/**
 * Returns class on index in the parameterized type on <code>clazz</code> or
 * <code>super</code>./*from   www . ja v  a2s  .  c  o  m*/
 *
 * @param clazz
 * @param index
 * @return
 */
public static Class<?> getIndexClass(final Class<?> clazz, final int index) {
    if (clazz.getGenericSuperclass() instanceof ParameterizedType) {
        final ParameterizedType type = (ParameterizedType) clazz.getGenericSuperclass();
        DeclaredType declaredType = null;
        if (type.getActualTypeArguments().length > index + 1) {
            declaredType = getDeclaredType(clazz, type.getActualTypeArguments()[index]);
        } else {
            declaredType = getDeclaredType(clazz,
                    type.getActualTypeArguments()[type.getActualTypeArguments().length - 1]);
        }
        return (Class<?>) declaredType.getType();
    } else if (clazz.getGenericSuperclass() instanceof Class) {
        return getIndexClass(clazz.getSuperclass(), index);
    } else {
        return null;
    }
}