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.clark.func.Functions.java

/**
 * <p>/*from  www . j  a v a2 s.  c om*/
 * </p>
 * 
 * @param cls
 * @param toClass
 * @param subtypeVarAssigns
 * @return
 */
private static Map<TypeVariable<?>, Type> getTypeArguments(Class<?> cls, Class<?> toClass,
        Map<TypeVariable<?>, Type> subtypeVarAssigns) {
    // make sure they're assignable
    if (!isAssignable(cls, toClass)) {
        return null;
    }

    // can't work with primitives
    if (cls.isPrimitive()) {
        // both classes are primitives?
        if (toClass.isPrimitive()) {
            // dealing with widening here. No type arguments to be
            // harvested with these two types.
            return new HashMap<TypeVariable<?>, Type>();
        }

        // work with wrapper the wrapper class instead of the primitive
        cls = primitiveToWrapper(cls);
    }

    // create a copy of the incoming map, or an empty one if it's null
    HashMap<TypeVariable<?>, Type> typeVarAssigns = subtypeVarAssigns == null
            ? new HashMap<TypeVariable<?>, Type>()
            : new HashMap<TypeVariable<?>, Type>(subtypeVarAssigns);

    // no arguments for the parameters, or target class has been reached
    if (cls.getTypeParameters().length > 0 || toClass.equals(cls)) {
        return typeVarAssigns;
    }

    // walk the inheritance hierarchy until the target class is reached
    return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
}

From source file:com.clark.func.Functions.java

/**
 * <p>//from www  .j  av  a 2s.c  o  m
 * </p>
 * 
 * @param parameterizedType
 * @param toClass
 * @param subtypeVarAssigns
 * @return
 */
private static Map<TypeVariable<?>, Type> getTypeArguments(ParameterizedType parameterizedType,
        Class<?> toClass, Map<TypeVariable<?>, Type> subtypeVarAssigns) {
    Class<?> cls = getRawType(parameterizedType);

    // make sure they're assignable
    if (!isAssignable(cls, toClass)) {
        return null;
    }

    Type ownerType = parameterizedType.getOwnerType();
    Map<TypeVariable<?>, Type> typeVarAssigns;

    if (ownerType instanceof ParameterizedType) {
        // get the owner type arguments first
        ParameterizedType parameterizedOwnerType = (ParameterizedType) ownerType;
        typeVarAssigns = getTypeArguments(parameterizedOwnerType, getRawType(parameterizedOwnerType),
                subtypeVarAssigns);
    } else {
        // no owner, prep the type variable assignments map
        typeVarAssigns = subtypeVarAssigns == null ? new HashMap<TypeVariable<?>, Type>()
                : new HashMap<TypeVariable<?>, Type>(subtypeVarAssigns);
    }

    // get the subject parameterized type's arguments
    Type[] typeArgs = parameterizedType.getActualTypeArguments();
    // and get the corresponding type variables from the raw class
    TypeVariable<?>[] typeParams = cls.getTypeParameters();

    // map the arguments to their respective type variables
    for (int i = 0; i < typeParams.length; i++) {
        Type typeArg = typeArgs[i];
        typeVarAssigns.put(typeParams[i],
                typeVarAssigns.containsKey(typeArg) ? typeVarAssigns.get(typeArg) : typeArg);
    }

    if (toClass.equals(cls)) {
        // target class has been reached. Done.
        return typeVarAssigns;
    }

    // walk the inheritance hierarchy until the target class is reached
    return getTypeArguments(getClosestParentType(cls, toClass), toClass, typeVarAssigns);
}

From source file:com.clark.func.Functions.java

/**
 * <p>// w ww . j av a2s  . co m
 * </p>
 * 
 * @param cls
 * @param parameterizedType
 * @param typeVarAssigns
 */
private static <T> void mapTypeVariablesToArguments(Class<T> cls, ParameterizedType parameterizedType,
        Map<TypeVariable<?>, Type> typeVarAssigns) {
    // capture the type variables from the owner type that have assignments
    Type ownerType = parameterizedType.getOwnerType();

    if (ownerType instanceof ParameterizedType) {
        // recursion to make sure the owner's owner type gets processed
        mapTypeVariablesToArguments(cls, (ParameterizedType) ownerType, typeVarAssigns);
    }

    // parameterizedType is a generic interface/class (or it's in the owner
    // hierarchy of said interface/class) implemented/extended by the class
    // cls. Find out which type variables of cls are type arguments of
    // parameterizedType:
    Type[] typeArgs = parameterizedType.getActualTypeArguments();

    // of the cls's type variables that are arguments of parameterizedType,
    // find out which ones can be determined from the super type's arguments
    TypeVariable<?>[] typeVars = getRawType(parameterizedType).getTypeParameters();

    // use List view of type parameters of cls so the contains() method can
    // be used:
    List<TypeVariable<Class<T>>> typeVarList = Arrays.asList(cls.getTypeParameters());

    for (int i = 0; i < typeArgs.length; i++) {
        TypeVariable<?> typeVar = typeVars[i];
        Type typeArg = typeArgs[i];

        // argument of parameterizedType is a type variable of cls
        if (typeVarList.contains(typeArg)
                // type variable of parameterizedType has an assignment in
                // the super type.
                && typeVarAssigns.containsKey(typeVar)) {
            // map the assignment to the cls's type variable
            typeVarAssigns.put((TypeVariable<?>) typeArg, typeVarAssigns.get(typeVar));
        }
    }
}

From source file:nl.luminis.test.util.annotations.HierarchyDiscovery.java

private Type resolveType(Class<?> clazz) {
    if (clazz.getTypeParameters().length > 0) {
        TypeVariable<?>[] actualTypeParameters = clazz.getTypeParameters();

        return TypeUtils.parameterizeWithOwner(clazz.getDeclaringClass(), clazz, actualTypeParameters);
    } else {/*from w  ww . j a v a2s.  co  m*/
        return clazz;
    }
}

From source file:nl.luminis.test.util.annotations.HierarchyDiscovery.java

private Type resolveTypeParameter(ParameterizedType type, Type beanType, TypeVariable<?> typeVariable) {
    // step1. raw type
    Class<?> actualType = (Class<?>) type.getRawType();
    TypeVariable<?>[] typeVariables = actualType.getTypeParameters();
    Type[] actualTypes = type.getActualTypeArguments();
    for (int i = 0; i < typeVariables.length; i++) {
        if (typeVariables[i].equals(typeVariable) && !actualTypes[i].equals(typeVariable)) {
            return resolveType(this.type, beanType, actualTypes[i]);
        }//from  w  w w  .  j a v  a2s .  co m
    }

    // step2. generic super class
    Type genericSuperType = actualType.getGenericSuperclass();
    Type resolvedGenericSuperType = resolveType(genericSuperType, beanType, typeVariable);
    if (!(resolvedGenericSuperType instanceof TypeVariable<?>)) {
        return resolvedGenericSuperType;
    }

    // step3. generic interfaces
    if (beanType instanceof ParameterizedType) {
        for (Type interfaceType : ((Class<?>) ((ParameterizedType) beanType).getRawType())
                .getGenericInterfaces()) {
            Type resolvedType = resolveType(interfaceType, interfaceType, typeVariable);
            if (!(resolvedType instanceof TypeVariable<?>)) {
                return resolvedType;
            }
        }
    }

    // don't resolve type variable
    return typeVariable;
}

From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java

private static void validateLambdaGenericParameter(Type t) {
    if (!(t instanceof Class)) {
        return;// ww  w. j  av  a  2  s.c  o  m
    }
    final Class<?> clazz = (Class<?>) t;

    if (clazz.getTypeParameters().length > 0) {
        throw new InvalidTypesException("The generic type parameters of '" + clazz.getSimpleName()
                + "' are missing. \n"
                + "It seems that your compiler has not stored them into the .class file. \n"
                + "Currently, only the Eclipse JDT compiler preserves the type information necessary to use the lambdas feature type-safely. \n"
                + "See the documentation for more information about how to compile jobs containing lambda expressions.");
    }
}

From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java

/**
 * Tries to find a concrete value (Class, ParameterizedType etc. ) for a TypeVariable by traversing the type hierarchy downwards.
 * If a value could not be found it will return the most bottom type variable in the hierarchy.
 *//* w w  w .  j  av  a  2 s.co m*/
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 (sameTypeVars(curVarOfCurT, inTypeTypeVar)) {
                    Type curVarType = ((ParameterizedType) curT).getActualTypeArguments()[paramIndex];

                    // another type variable level
                    if (curVarType instanceof TypeVariable<?>) {
                        inTypeTypeVar = (TypeVariable<?>) curVarType;
                    }
                    // class
                    else {
                        return curVarType;
                    }
                }
            }
        }
    }
    // can not be materialized, most likely due to type erasure
    // return the type variable of the deepest level
    return inTypeTypeVar;
}

From source file:org.apache.pig.EvalFunc.java

public EvalFunc() {
    // Resolve concrete type for T of EvalFunc<T>
    // 1. Build map from type param to type for class hierarchy from current class to EvalFunc
    Map<TypeVariable<?>, Type> typesByTypeVariable = new HashMap<TypeVariable<?>, Type>();
    Class<?> cls = getClass();
    Type type = cls.getGenericSuperclass();
    cls = cls.getSuperclass();/* w w  w. j  av a  2  s . co  m*/
    while (EvalFunc.class.isAssignableFrom(cls)) {
        TypeVariable<? extends Class<?>>[] typeParams = cls.getTypeParameters();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Type[] typeArgs = pType.getActualTypeArguments();
            for (int i = 0; i < typeParams.length; i++) {
                typesByTypeVariable.put(typeParams[i], typeArgs[i]);
            }
        }
        type = cls.getGenericSuperclass();
        cls = cls.getSuperclass();
    }

    // 2. Use type param to type map to determine concrete type of for T of EvalFunc<T>
    Type targetType = EvalFunc.class.getTypeParameters()[0];
    while (targetType != null && targetType instanceof TypeVariable) {
        targetType = typesByTypeVariable.get(targetType);
    }
    if (targetType == null || targetType instanceof GenericArrayType || targetType instanceof WildcardType) {
        throw new RuntimeException(String.format(
                "Failed to determine concrete type for type parameter T of EvalFunc<T> for derived class '%s'",
                getClass().getName()));
    }
    returnType = targetType;

    // Type check the initial, intermediate, and final functions
    if (this instanceof Algebraic) {
        Algebraic a = (Algebraic) this;

        String errMsg = "function of " + getClass().getName() + " is not of the expected type.";
        if (getReturnTypeFromSpec(new FuncSpec(a.getInitial())) != Tuple.class)
            throw new RuntimeException("Initial " + errMsg);
        if (getReturnTypeFromSpec(new FuncSpec(a.getIntermed())) != Tuple.class)
            throw new RuntimeException("Intermediate " + errMsg);
        if (!getReturnTypeFromSpec(new FuncSpec(a.getFinal())).equals(returnType))
            throw new RuntimeException("Final " + errMsg);
    }

}

From source file:org.apache.ranger.service.RangerBaseModelService.java

@SuppressWarnings("unchecked")
public RangerBaseModelService() {
    Class klass = getClass();
    ParameterizedType genericSuperclass = (ParameterizedType) klass.getGenericSuperclass();
    TypeVariable<Class<?>> var[] = klass.getTypeParameters();

    if (genericSuperclass.getActualTypeArguments()[0] instanceof Class) {
        tEntityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
        tViewClass = (Class<V>) genericSuperclass.getActualTypeArguments()[1];
    } else if (var.length > 0) {
        tEntityClass = (Class<T>) var[0].getBounds()[0];
        tViewClass = (Class<V>) var[1].getBounds()[0];
    } else {/*from ww  w .  j  av a2 s  . c  o m*/
        LOG.fatal("Cannot find class for template", new Throwable());
    }

    if (tEntityClass != null) {
        tClassName = tEntityClass.getName();
    }

    populateExistingBaseFields = false;

    countQueryStr = "SELECT COUNT(obj) FROM " + tClassName + " obj ";
    queryStr = "SELECT obj FROM " + tClassName + " obj ";
}

From source file:org.batoo.common.reflect.ReflectHelper.java

private static Class<?> getTypeImpl(Class<?> clazz, Class<?> originalType, String methodName,
        List<Type> arguments) {
    final Map<TypeVariable<?>, Type> typeMap = Maps.newHashMap();

    if (arguments.size() > 0) {
        final TypeVariable<?>[] typeParameters = clazz.getTypeParameters();
        for (int i = 0; i < typeParameters.length; i++) {
            typeMap.put(typeParameters[i], arguments.get(i));
        }/*ww  w  .j  a v a  2 s  .  co m*/
    }

    try {
        final Method m = clazz.getDeclaredMethod(methodName);

        final Type type = typeMap.get(m.getGenericReturnType());
        if (type != null) {
            return ReflectHelper.checkAndReturn(originalType, m, (Class<?>) type);
        }

        return ReflectHelper.checkAndReturn(originalType, m, m.getReturnType());
    } catch (final NoSuchMethodException e) {
        final List<Type> typeArguments = Lists.newArrayList();

        if (clazz.getGenericSuperclass() instanceof ParameterizedType) {
            final ParameterizedType parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();

            for (final Type typeArgument : parameterizedType.getActualTypeArguments()) {
                if (typeArgument instanceof TypeVariable) {
                    typeArguments.add(typeMap.get(typeArgument));
                } else {
                    typeArguments.add(typeArgument);
                }
            }
        }

        final Class<?> superclass = clazz.getSuperclass();

        if (superclass == Object.class) {
            return originalType;
        }

        return ReflectHelper.getTypeImpl(superclass, originalType, methodName, typeArguments);
    }
}