Example usage for java.lang Class getTypeParameters

List of usage examples for java.lang Class getTypeParameters

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public TypeVariable<Class<T>>[] getTypeParameters() 

Source Link

Document

Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.

Usage

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 ww  w .jav a  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:io.coala.factory.ClassUtil.java

/**
 * Get the actual type arguments a child class has used to extend a generic
 * base class. See <a/*from w w  w .j  av a 2 s. c  om*/
 * href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860"
 * >description</a>
 * 
 * @param genericAncestorType the base class
 * @param concreteDescendantType the child class
 * @return a list of the raw classes for the actual type arguments.
 */
public static <T> List<Class<?>> getTypeArguments(final Class<T> genericAncestorType,
        final Class<? extends T> concreteDescendantType) {
    // sanity check
    if (genericAncestorType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("genericAncestorType");
    if (concreteDescendantType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("concreteDescendantType");

    Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
    Type type = concreteDescendantType;
    Class<?> typeClass = getClass(type);

    // start walking up the inheritance hierarchy until we hit parentClass
    while (!genericAncestorType.equals(typeClass)) {
        if (type instanceof Class) {
            // there is no useful information for us in raw types, so just
            // keep going.

            if (genericAncestorType.isInterface()) {
                Type intfType = null;
                for (Type intf : typeClass.getGenericInterfaces()) {
                    if (intf instanceof ParameterizedType
                            && genericAncestorType.equals(((ParameterizedType) intf).getRawType())) {
                        intfType = intf;
                        break;
                    }
                }
                if (intfType == null)
                    type = typeClass.getGenericSuperclass();
                else
                    type = intfType;
            } else
                type = typeClass.getGenericSuperclass();

            if (type == null) {
                if (!typeClass.isInterface()) {
                    LOG.warn("No generic super classes found for child class: " + typeClass + " of parent: "
                            + genericAncestorType);
                    return Collections.emptyList();
                }
                for (Type intf : typeClass.getGenericInterfaces()) {
                    if (intf instanceof ParameterizedType) {
                        type = intf;
                        // TODO try other interfaces if this one fails?
                        break;
                    }
                }
                if (type == null) {
                    LOG.warn("No generic ancestors found for child interface: " + typeClass + " of parent: "
                            + genericAncestorType);
                    return Collections.emptyList();
                }
            }
            // LOG.trace(String.format("Trying generic super of %s: %s",
            // typeClass.getSimpleName(), type));
        } else {
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            final Class<?> rawType = (Class<?>) parameterizedType.getRawType();

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

            if (!genericAncestorType.equals(rawType)) {
                type = rawType.getGenericSuperclass();
                // LOG.trace(String.format(
                // "Trying generic super of child %s: %s", rawType,
                // type));
            }
            // else // done climbing the hierarchy
            // LOG.trace("Matched generic " + type + " to ancestor: "
            // + genericAncestorType);
        }
        typeClass = getClass(type);
        // LOG.trace("Trying generic " + typeClass + " from: "
        // + Arrays.asList(typeClass.getGenericInterfaces()));
    }

    // finally, for each actual type argument provided to baseClass,
    // determine (if possible)
    // the raw class for that type argument.
    final Type[] actualTypeArguments;
    if (type instanceof Class) {
        actualTypeArguments = typeClass.getTypeParameters();
    } else {
        actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
    }

    // resolve types by chasing down type variables.
    final List<Class<?>> parentTypeArguments = new ArrayList<Class<?>>();
    for (Type baseType : actualTypeArguments) {
        while (resolvedTypes.containsKey(baseType))
            baseType = resolvedTypes.get(baseType);

        parentTypeArguments.add(getClass(baseType));
    }
    // LOG.trace(String.format(
    // "Got child %s's type arguments for %s: %s",
    // childClass.getName(), parentClass.getSimpleName(),
    // parentTypeArguments));
    return parentTypeArguments;
}

From source file:jp.go.nict.langrid.servicecontainer.handler.jsonrpc.servlet.JsonRpcServlet.java

private static void appendGenericsInfo(Class<?> clazz, StringBuilder b) {
    for (TypeVariable<? extends GenericDeclaration> v : clazz.getTypeParameters()) {
        if (b.length() == 0) {
            b.append("&lt;");
        } else {/*from w ww . j  a va2  s.c om*/
            b.append(",");
        }
        b.append(v.getName());
    }
    if (b.length() != 0)
        b.append("&gt;");
}

From source file:eu.stratosphere.api.java.typeutils.TypeExtractor.java

private static Type materializeTypeVariable(ArrayList<Type> typeHierarchy, TypeVariable<?> typeVar) {

    TypeVariable<?> inTypeTypeVar = typeVar;
    // iterate thru hierarchy from top to bottom until type variable gets a class assigned
    for (int i = typeHierarchy.size() - 1; i >= 0; i--) {
        Type curT = typeHierarchy.get(i);

        // parameterized type
        if (curT instanceof ParameterizedType) {
            Class<?> rawType = ((Class<?>) ((ParameterizedType) curT).getRawType());

            for (int paramIndex = 0; paramIndex < rawType.getTypeParameters().length; paramIndex++) {

                TypeVariable<?> curVarOfCurT = rawType.getTypeParameters()[paramIndex];

                // check if variable names match
                if (curVarOfCurT.getName().equals(inTypeTypeVar.getName())
                        && curVarOfCurT.getGenericDeclaration().equals(inTypeTypeVar.getGenericDeclaration())) {
                    Type curVarType = ((ParameterizedType) curT).getActualTypeArguments()[paramIndex];

                    // another type variable level
                    if (curVarType instanceof TypeVariable<?>) {
                        inTypeTypeVar = (TypeVariable<?>) curVarType;
                    }/*  www.j  a v a  2s .  co  m*/
                    // class
                    else {
                        return curVarType;
                    }
                }
            }
        }
    }
    // can not be materialized, most likely due to type erasure
    return null;
}

From source file:jp.terasoluna.fw.util.GenericsUtil.java

/**
 * ??<code>Type</code>??//from w ww .ja  v  a2 s. com
 * @param type ????<code>Type</code>
 * @param ancestorTypeList <code>type</code>??? ??????<code>ParameterizedType</code>?
 * @return ?
 * @throws IllegalStateException <code>type</code>? <code>Class</code>???? <code>TypeVariable</code>????? 
 *             <code>type</code>?? ????????? <code>type</code>???<code>Class</code>????
 *             (??)?
 */
protected static Class<? extends Object> resolveTypeVariable(Type type,
        List<ParameterizedType> ancestorTypeList) throws IllegalStateException {

    if (isNotTypeVariable(type)) {
        return getRawClass(type);
    }

    // TypeVariable:?
    TypeVariable<?> targetType = (TypeVariable<?>) type;
    Type actualType = null;
    for (int i = ancestorTypeList.size() - 1; i >= 0; i--) {
        ParameterizedType ancestorType = ancestorTypeList.get(i);

        // ?????
        GenericDeclaration declaration = targetType.getGenericDeclaration();
        if (!(declaration instanceof Class)) {
            throw new IllegalStateException("TypeVariable(" + targetType.getName()
                    + " is not declared at Class " + "(ie. is declared at Method or Constructor)");
        }

        // ?Generics????????
        Class<?> declaredClass = (Class<?>) declaration;
        if (declaredClass != ancestorType.getRawType()) {
            continue;
        }

        // ????????
        // ConcreteAbstractBLogic<R,P> extends AbstractBLogic<P,R>
        // ????????type????
        Type[] parameterTypes = declaredClass.getTypeParameters();
        int index = ArrayUtils.indexOf(parameterTypes, targetType);
        if (index == -1) {
            // ???????????????
            // ??????????
            // ???Generics?API?????????????
            // ?????????
            throw new IllegalStateException("Class(" + declaredClass.getName()
                    + ") does not declare TypeValidable(" + targetType.getName() + ")");
        }
        actualType = ancestorType.getActualTypeArguments()[index];
        if (log.isDebugEnabled()) {
            log.debug("resolved " + targetType.getName() + " -> " + actualType);
        }

        if (isNotTypeVariable(actualType)) {
            return getRawClass(actualType);
        }
        targetType = (TypeVariable<?>) actualType;
    }

    throw new IllegalStateException(
            "Concrete type of Type(" + type + ") was not found in ancestorList(" + ancestorTypeList + ")");
}

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/* www .ja va  2 s  . c  om*/
 */
@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:GenericClass.java

private GenericClass(Class<?> concrete) {
    TypeVariable<?>[] parameters = concrete.getTypeParameters();
    // if (parameters.length > 0) throw new MagmaException("Cannot parse {0}, it
    // is a generic class, use a concrete class instead", concrete);
    myclass = concrete;/*from w  ww  .ja va2 s .co m*/
    recurse(concrete);
    coalesceMap();
}

From source file:Main.java

private final static Type resolveTypeVariable(TypeVariable<? extends GenericDeclaration> type,
        Class<?> declaringClass, Class<?> inClass) {

    if (inClass == null)
        return null;

    Class<?> superClass = null;
    Type resolvedType = null;//  w  w w . j  a  v a2  s. c  o m
    Type genericSuperClass = null;

    if (!declaringClass.equals(inClass)) {
        if (declaringClass.isInterface()) {
            // the declaringClass is an interface
            Class<?>[] interfaces = inClass.getInterfaces();
            for (int i = 0; i < interfaces.length && resolvedType == null; i++) {
                superClass = interfaces[i];
                resolvedType = resolveTypeVariable(type, declaringClass, superClass);
                genericSuperClass = inClass.getGenericInterfaces()[i];
            }
        }

        if (resolvedType == null) {
            superClass = inClass.getSuperclass();
            resolvedType = resolveTypeVariable(type, declaringClass, superClass);
            genericSuperClass = inClass.getGenericSuperclass();
        }
    } else {
        resolvedType = type;
        genericSuperClass = superClass = inClass;

    }

    if (resolvedType != null) {
        // if its another type this means we have finished
        if (resolvedType instanceof TypeVariable<?>) {
            type = (TypeVariable<?>) resolvedType;
            TypeVariable<?>[] parameters = superClass.getTypeParameters();
            int positionInClass = 0;
            for (; positionInClass < parameters.length
                    && !type.equals(parameters[positionInClass]); positionInClass++) {
            }

            // we located the position of the typevariable in the superclass
            if (positionInClass < parameters.length) {
                // let's look if we have type specialization information in the current class
                if (genericSuperClass instanceof ParameterizedType) {
                    ParameterizedType pGenericType = (ParameterizedType) genericSuperClass;
                    Type[] args = pGenericType.getActualTypeArguments();
                    return positionInClass < args.length ? args[positionInClass] : null;
                }
            }

            // we didnt find typevariable specialization in the class, so it's the best we can
            // do, lets return the resolvedType...
        }
    }

    return resolvedType;
}

From source file:GenericClass.java

private void recurse(Class<?> clazz, Class<?> simplesup, ParameterizedType partype) {
    Type[] typeArguments = partype.getActualTypeArguments();
    TypeVariable<?>[] parameters = simplesup.getTypeParameters();

    for (int i = 0; i < typeArguments.length; i++) {
        if (typeArguments[i] instanceof Class) {
            genericMap.put(simplesup.getName() + "--" + parameters[i].getName(), (Class) typeArguments[i]);
        } else if (typeArguments[i] instanceof TypeVariable) {
            reverseIntermediate.put(clazz.getName() + "--" + ((TypeVariable<?>) typeArguments[i]).getName(),
                    simplesup.getName() + "--" + parameters[i].getName());
        }/* w w  w  .j  av  a  2s .co  m*/
    }

    recurse(simplesup);
}

From source file:com.github.juanmf.java2plant.render.PlantRenderer.java

private void addClassTypeParams(StringBuilder sb, Class<?> aClass) {
    List<String> typeParams = new ArrayList<>();
    // TODO: we are leaving lower bounds out, e.g. <? super Integer>
    for (TypeVariable t : aClass.getTypeParameters()) {
        Type[] bounds = t.getBounds();
        String jointBounds = TypesHelper.getSimpleName(StringUtils.join(bounds, "&"));
        typeParams.add(t.getName() + " extends " + jointBounds);
    }/*from   w w w  . java2 s. c  o m*/
    if (0 < typeParams.size()) {
        sb.append(" <").append(StringUtils.join(typeParams, ", ")).append(">");
    }
}