Example usage for java.lang.reflect TypeVariable getGenericDeclaration

List of usage examples for java.lang.reflect TypeVariable getGenericDeclaration

Introduction

In this page you can find the example usage for java.lang.reflect TypeVariable getGenericDeclaration.

Prototype

D getGenericDeclaration();

Source Link

Document

Returns the GenericDeclaration object representing the generic declaration declared for this type variable.

Usage

From source file:jef.tools.reflect.ClassEx.java

public Type getImplType(TypeVariable<?> declaration) {
    if (declaration.getGenericDeclaration() == this.cls && this.genericType instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) genericType;
        int n = 0;
        for (TypeVariable<?> tv : cls.getTypeParameters()) {
            if (tv == declaration)
                break;
            n++;/*from  w  w  w  . j a  va  2s  .  c  om*/
        }
        return pType.getActualTypeArguments()[n];
    }
    return null;
}

From source file:org.datalorax.populace.core.util.TypeUtils.java

/**
 * Gets a single type argument from the set of type arguments of a class/interface based on a declaring class of the
 * supplied {@code typeVariable}.//from ww  w.  j a  v  a 2  s  . co  m
 *
 * For instance, given the parameterised type representing {@code Map&lt;String,Integer&gt;} and the
 * {@code typeVariable} of {@code Map.class.getTypeParameters()[0]}, then this method will return String.class.
 *
 * This method will work even if the type represented by {@code type} is a subtype of the required type and does
 * not itself have any template arguments. For example, this method will determine that both of the parameters for
 * the interface {@link Map} are {@link Object} for the subtype {@link java.util.Properties Properties} even though
 * the subtype does not directly implement the {@code Map} interface.
 *
 * If the parameterized {@code type}'s type arguments are {@link java.lang.reflect.TypeVariable}s or
 * {@link java.lang.reflect.WildcardType}, then these are returned.
 *
 * If the {@code type} is not a parameterised type, but a raw {@code Class}, and {@code typeVariable} is a valid
 * {@link java.lang.reflect.TypeVariable} of the type or its super type/interfaces, then the method will return the
 * {@link java.lang.reflect.Type type} representing the type argument. For example, if {@code type} is
 * {@code ArrayList.class} and {@code typeVariable} is {@code List.class.getTypeParameters()[0]}, then the method will
 * return the equivalent of {@code ArrayList.class.getTypeParameters()[0]}
 *
 * This method throws {@link java.lang.IllegalArgumentException} if {@code type} is not assignable to {@code toClass}.
 * It returns an Object.class if the actual type parameter can not be determined.
 *
 * @param type         the type from which to determine the type parameters of {@code toClass}
 * @param typeVariable the specific typeVariable of {@code toClass} to retrieve.
 * @return the {@code Class} of the type argument, or null if {@code type} is not assignable to {@code toClass}
 * @throws java.lang.IllegalArgumentException if {@code type} is not assignable to {@code toClass}.
 */
public static Type getTypeArgument(final Type type, final TypeVariable<? extends Class<?>> typeVariable) {
    final Class<?> toClass = typeVariable.getGenericDeclaration();
    if (toClass.equals(type)) {
        return typeVariable;
    }

    final Map<TypeVariable<?>, Type> typeArguments = org.apache.commons.lang3.reflect.TypeUtils
            .getTypeArguments(type, toClass);
    if (typeArguments == null) {
        throw new IllegalArgumentException(type + " is not assignable to " + toClass);
    }

    final Type typeArg = typeArguments.get(typeVariable);
    return typeArg == null ? Object.class : typeArg;
}

From source file:org.evosuite.utils.generic.GenericAccessibleObject.java

/**
 * Set type parameters based on return type
 * /*from w w w .j a  v a 2 s .  c o  m*/
 * @param returnType
 * @return
 * @throws ConstructionFailedException
 */
public T getGenericInstantiationFromReturnValue(GenericClass generatedType) throws ConstructionFailedException {

    logger.debug("Instantiating generic return for generated Type " + generatedType);
    T copy = copy();

    // We just want to have the type variables defined in the generic method here
    // and not type variables defined in the owner
    Map<TypeVariable<?>, Type> concreteTypes = new HashMap<TypeVariable<?>, Type>();
    logger.debug("Getting type map of generated type");
    Map<TypeVariable<?>, Type> generatorTypes = generatedType.getTypeVariableMap();
    logger.debug("Got type map of generated type: " + generatorTypes);
    Type genericReturnType = getGenericGeneratedType();

    logger.debug(
            "Getting generic instantiation for return type " + generatedType + " of method: " + toString());

    if (genericReturnType instanceof ParameterizedType && generatedType.isParameterizedType()) {
        logger.debug("Return value is a parameterized type, matching variables");
        generatorTypes.putAll(GenericUtils.getMatchingTypeParameters(
                (ParameterizedType) generatedType.getType(), (ParameterizedType) genericReturnType));
    } else if (genericReturnType instanceof TypeVariable<?>) {
        generatorTypes.put((TypeVariable<?>) genericReturnType, generatedType.getType());
    }

    if (genericReturnType instanceof ParameterizedType) {
        for (Type parameterType : getGenericParameterTypes()) {
            logger.debug("Checking parameter " + parameterType);
            if (parameterType instanceof ParameterizedType) {
                Map<TypeVariable<?>, Type> matchedMap = GenericUtils.getMatchingTypeParameters(
                        (ParameterizedType) parameterType, (ParameterizedType) genericReturnType);
                for (TypeVariable<?> var : matchedMap.keySet()) {
                    if (!generatorTypes.containsKey(var))
                        generatorTypes.put(var, matchedMap.get(var));
                }
                logger.debug("Map is now " + generatorTypes);
            }
        }
    }
    logger.debug("GeneratorTypes is now: " + generatorTypes);
    List<TypeVariable<?>> parameters = Arrays.asList(getTypeParameters());
    for (TypeVariable<?> var : generatorTypes.keySet()) {
        if (parameters.contains(var) && !(generatorTypes.get(var) instanceof WildcardType)) {
            logger.debug("Parameter " + var + " in map, adding to concrete types: " + generatorTypes.get(var));
            concreteTypes.put(var, generatorTypes.get(var));
        } else {
            logger.debug("Parameter " + var + " not in map, not adding to concrete types: "
                    + generatorTypes.get(var));
            logger.debug("Key: " + var.getGenericDeclaration());
            for (TypeVariable<?> k : parameters) {
                logger.debug("Param: " + k.getGenericDeclaration());
            }
        }
    }

    // When resolving the type variables on a non-static generic method
    // we need to look at the owner type, and not the return type!

    List<GenericClass> typeParameters = new ArrayList<GenericClass>();
    logger.debug("Setting parameters with map: " + concreteTypes);
    for (TypeVariable<?> parameter : getTypeParameters()) {
        GenericClass concreteType = new GenericClass(parameter);
        logger.debug("(I) Setting parameter " + parameter + " to type " + concreteType.getTypeName());
        GenericClass instantiation = concreteType.getGenericInstantiation(concreteTypes);
        logger.debug("Got instantiation for " + parameter + ": " + instantiation);
        if (!instantiation.satisfiesBoundaries(parameter, concreteTypes)) {
            logger.info("Type parameter does not satisfy boundaries: " + parameter + " " + instantiation);
            logger.info(Arrays.asList(parameter.getBounds()).toString());
            logger.info(instantiation.toString());
            throw new ConstructionFailedException("Type parameter does not satisfy boundaries: " + parameter);
        }
        typeParameters.add(instantiation);
    }
    copy.setTypeParameters(typeParameters);
    copy.owner = copy.getOwnerClass().getGenericInstantiation(concreteTypes);

    return copy;
}

From source file:org.evosuite.utils.generic.GenericUtils.java

/**
 * TODO: Try to match p2 superclasses? /*w  w  w .j  av  a 2 s  .com*/
 * 
 * @param p1 Desired TypeVariable assignment
 * @param p2 Generic type with the TypeVariables that need assignment
 * @return
 */
public static Map<TypeVariable<?>, Type> getMatchingTypeParameters(ParameterizedType p1, ParameterizedType p2) {
    logger.debug("Matching generic types between " + p1 + " and " + p2);
    Map<TypeVariable<?>, Type> map = new HashMap<TypeVariable<?>, Type>();
    if (!p1.getRawType().equals(p2.getRawType())) {
        logger.debug("Raw types do not match!");

        GenericClass ownerClass = new GenericClass(p2);

        if (GenericClass.isSubclass(p1.getRawType(), p2.getRawType())) {
            logger.debug(p1 + " is a super type of " + p2);
            Map<TypeVariable<?>, Type> commonsMap = TypeUtils.determineTypeArguments((Class<?>) p2.getRawType(),
                    p1);
            logger.debug("Adding to map: " + commonsMap);
            // TODO: Now we would need to iterate over the type parameters, and update the map?
            //map.putAll(commonsMap);

            for (TypeVariable<?> t : map.keySet()) {
                logger.debug(t + ": " + t.getGenericDeclaration());
            }

            // For each type variable of the raw type, map the parameter type to that type
            Type[] p2TypesA = ((Class<?>) p2.getRawType()).getTypeParameters();
            Type[] p2TypesB = p2.getActualTypeArguments();
            for (int i = 0; i < p2TypesA.length; i++) {
                Type a = p2TypesA[i];
                Type b = p2TypesB[i];
                logger.debug("Should be mapping " + a + " and " + b);
                if (a instanceof TypeVariable<?>) {
                    logger.debug(a + " is a type variable: " + ((TypeVariable<?>) a).getGenericDeclaration());
                    if (b instanceof TypeVariable<?>) {
                        logger.debug(
                                b + " is a type variable: " + ((TypeVariable<?>) b).getGenericDeclaration());
                        if (commonsMap.containsKey((TypeVariable<?>) a)
                                && !(commonsMap.get((TypeVariable<?>) a) instanceof WildcardType)
                                && !(commonsMap.get((TypeVariable<?>) a) instanceof TypeVariable<?>))
                            map.put((TypeVariable<?>) b, commonsMap.get((TypeVariable<?>) a));
                        //else
                        //   map.put((TypeVariable<?>)a, b);
                    }
                }

                //               if(b instanceof TypeVariable<?>) {
                //                  if(map.containsKey(a))
                //                     map.put((TypeVariable<?>)b, map.get(a));
                //                  //else
                //                  //   map.put((TypeVariable<?>)b, a);
                //               }

                logger.debug("Updated map: " + map);
            }

        }

        for (GenericClass interfaceClass : ownerClass.getInterfaces()) {
            if (interfaceClass.isParameterizedType())
                map.putAll(getMatchingTypeParameters(p1, (ParameterizedType) interfaceClass.getType()));
            else
                logger.debug("Interface " + interfaceClass + " is not parameterized");
        }
        if (ownerClass.getRawClass().getSuperclass() != null) {
            GenericClass ownerSuperClass = ownerClass.getSuperClass();
            if (ownerSuperClass.isParameterizedType())
                map.putAll(getMatchingTypeParameters(p1, (ParameterizedType) ownerSuperClass.getType()));
            else
                logger.debug("Super type " + ownerSuperClass + " is not parameterized");
        }
        return map;
    }

    for (int i = 0; i < p1.getActualTypeArguments().length; i++) {
        Type t1 = p1.getActualTypeArguments()[i];
        Type t2 = p2.getActualTypeArguments()[i];
        if (t1 == t2)
            continue;
        logger.debug("First match: " + t1 + " - " + t2);
        if (t1 instanceof TypeVariable<?>) {
            map.put((TypeVariable<?>) t1, t2);
        }
        if (t2 instanceof TypeVariable<?>) {
            map.put((TypeVariable<?>) t2, t1);
        } else if (t2 instanceof ParameterizedType && t1 instanceof ParameterizedType) {
            map.putAll(getMatchingTypeParameters((ParameterizedType) t1, (ParameterizedType) t2));
        }
        logger.debug("Updated map: " + map);

    }

    if (p1.getOwnerType() != null && p1.getOwnerType() instanceof ParameterizedType
            && p2.getOwnerType() instanceof ParameterizedType) {
        map.putAll(getMatchingTypeParameters((ParameterizedType) p1.getOwnerType(),
                (ParameterizedType) p2.getOwnerType()));
    }

    return map;
}

From source file:org.evosuite.utils.GenericClass.java

/**
 * Return a list of type variables of this type, or an empty list if this is
 * not a parameterized type/*from   w w  w.java  2 s.  c o  m*/
 * 
 * @return
 */
public List<TypeVariable<?>> getTypeVariables() {
    List<TypeVariable<?>> typeVariables = new ArrayList<TypeVariable<?>>();
    if (type instanceof ParameterizedType) {
        logger.debug("Type variables of {}: ", rawClass);
        for (TypeVariable<?> var : rawClass.getTypeParameters()) {
            logger.debug("Var {} of {}", var, var.getGenericDeclaration());
        }
        typeVariables.addAll(Arrays.asList(rawClass.getTypeParameters()));
    }
    return typeVariables;
}

From source file:org.evosuite.utils.GenericClass.java

/**
 * Determine whether the boundaries of the type variable are satisfied by
 * this class/* ww  w  .j  ava2  s  .  c  o  m*/
 * 
 * @param typeVariable
 * @return
 */
public boolean satisfiesBoundaries(TypeVariable<?> typeVariable, Map<TypeVariable<?>, Type> typeMap) {
    boolean isAssignable = true;
    logger.debug("Checking class: {} against type variable {} with map {}", type, typeVariable, typeMap);
    Map<TypeVariable<?>, Type> ownerVariableMap = getTypeVariableMap();
    for (Type bound : typeVariable.getBounds()) {
        if (bound instanceof ParameterizedType) {
            Class<?> boundClass = GenericTypeReflector.erase(bound);
            if (boundClass.isAssignableFrom(rawClass)) {
                Map<TypeVariable<?>, Type> xmap = TypeUtils.determineTypeArguments(rawClass,
                        (ParameterizedType) bound);
                ownerVariableMap.putAll(xmap);
            }
        }
    }
    ownerVariableMap.putAll(typeMap);
    boolean changed = true;
    while (changed) {
        changed = false;
        for (TypeVariable<?> var : ownerVariableMap.keySet()) {
            logger.debug("Type var: {} of {}", var, var.getGenericDeclaration());
            if (ownerVariableMap.get(var) instanceof TypeVariable<?>) {
                logger.debug("Is set to type var: {} of {}", ownerVariableMap.get(var),
                        ((TypeVariable<?>) ownerVariableMap.get(var)).getGenericDeclaration());
                TypeVariable<?> value = (TypeVariable<?>) ownerVariableMap.get(var);
                if (ownerVariableMap.containsKey(value)) {
                    logger.debug("Replacing {} with {}", var, ownerVariableMap.get(value));
                    ownerVariableMap.put(var, ownerVariableMap.get(value));
                    changed = true;
                } else {
                    logger.debug("Not in map: {}", value);
                }
            } else {
                logger.debug("Is set to concrete type: {}", ownerVariableMap.get(var));
            }
        }
        logger.debug("Current iteration of map: {}", ownerVariableMap);
    }

    GenericClass concreteClass = new GenericClass(GenericUtils.replaceTypeVariables(type, ownerVariableMap));
    logger.debug("Concrete class after variable replacement: {}", concreteClass);

    for (Type theType : typeVariable.getBounds()) {
        logger.debug("Current boundary of {}: {}", typeVariable, theType);
        // Special case: Enum is defined as Enum<T extends Enum>
        if (GenericTypeReflector.erase(theType).equals(Enum.class)) {
            logger.debug("Is ENUM case");
            // if this is an enum then it's ok. 
            if (isEnum()) {
                logger.debug("Class {} is an enum!", toString());

                continue;
            } else {
                // If it's not an enum, it cannot be assignable to enum!
                logger.debug("Class {} is not an enum.", toString());
                isAssignable = false;
                break;
            }
        }

        Type boundType = GenericUtils.replaceTypeVariables(theType, ownerVariableMap);
        boundType = GenericUtils.replaceTypeVariable(boundType, typeVariable, getType());
        boundType = GenericUtils.replaceTypeVariablesWithWildcards(boundType);

        logger.debug("Bound after variable replacement: {}", boundType);
        if (!concreteClass.isAssignableTo(boundType)) {
            logger.debug("Not assignable: {} and {}", type, boundType);
            // If the boundary is not assignable it may still be possible 
            // to instantiate the generic to an assignable type
            if (GenericTypeReflector.erase(boundType).isAssignableFrom(getRawClass())) {
                logger.debug("Raw classes are assignable: {}, {}", boundType, getRawClass());
                Type instanceType = GenericTypeReflector.getExactSuperType(boundType, getRawClass());
                if (instanceType == null) {
                    // This happens when the raw class is not a supertype 
                    // of the boundary
                    logger.debug("Instance type is null");
                    isAssignable = false;
                    break;
                }
                GenericClass instanceClass = new GenericClass(instanceType, getRawClass());

                logger.debug("Instance type is {}", instanceType);
                if (instanceClass.hasTypeVariables())
                    logger.debug("Instance type has type variables");
                if (instanceClass.hasWildcardTypes())
                    logger.debug("Instance type has wildcard variables");

                boundType = GenericUtils.replaceTypeVariable(theType, typeVariable, instanceType);
                logger.debug("Instance type after replacement is {}", boundType);
                if (GenericClass.isAssignable(boundType, instanceType)) {
                    logger.debug("Found assignable generic exact type: {}", instanceType);
                    continue;
                } else {
                    logger.debug("Is not assignable: {} and {}", boundType, instanceType);
                }
            }
            isAssignable = false;
            break;
        }
    }
    logger.debug("Result: is assignable {}", isAssignable);
    return isAssignable;
}

From source file:org.openflexo.antar.binding.TypeUtils.java

/**
 * Build instanciated DMType considering supplied type is generic (contains TypeVariable definitions) Returns a clone of DMType where
 * all references to TypeVariable are replaced by values defined in context type. For example, given type=Enumeration<E> and
 * context=Vector<String>, returns Enumeration<String> If supplied type is not generic, return type value (without cloning!)
 * /*from  w ww . ja  v  a 2s . co m*/
 * @param type
 *            : type to instanciate
 * @param context
 *            : context used to instanciate type
 * @return
 */
public static Type makeInstantiatedType(Type type, Type context) {
    if (type == null) {
        return null;
    }

    if (!isGeneric(type)) {
        return type;
    }

    if (type instanceof ParameterizedType) {
        Type[] actualTypeArguments = new Type[((ParameterizedType) type).getActualTypeArguments().length];
        for (int i = 0; i < ((ParameterizedType) type).getActualTypeArguments().length; i++) {
            actualTypeArguments[i] = makeInstantiatedType(
                    ((ParameterizedType) type).getActualTypeArguments()[i], context);
        }
        return new ParameterizedTypeImpl((Class) ((ParameterizedType) type).getRawType(), actualTypeArguments);
    }

    if (type instanceof GenericArrayType) {
        return new GenericArrayTypeImpl(
                makeInstantiatedType(((GenericArrayType) type).getGenericComponentType(), context));
    }

    if (type instanceof TypeVariable) {
        TypeVariable<GenericDeclaration> tv = (TypeVariable<GenericDeclaration>) type;
        GenericDeclaration gd = tv.getGenericDeclaration();
        // System.out.println("Found type variable "+tv+" name="+tv.getName()+" GD="+tv.getGenericDeclaration());
        if (gd instanceof Class) {
            if (context instanceof ParameterizedType) {
                for (int i = 0; i < gd.getTypeParameters().length; i++) {
                    if (gd.getTypeParameters()[i].equals(tv)) {
                        // Found matching parameterized type
                        if (i < ((ParameterizedType) context).getActualTypeArguments().length) {
                            // logger.info("********* return instantiatedType for "+type+" context="+context+" gd="+gd);
                            if (!((ParameterizedType) context).getRawType().equals(gd)) {
                                return makeInstantiatedType(type, getSuperType(context));
                            }
                            return ((ParameterizedType) context).getActualTypeArguments()[i];
                        } else {
                            logger.warning("Could not retrieve parameterized type " + tv + " with context "
                                    + simpleRepresentation(context));
                            return type;
                        }
                    }
                }
            } else if (context instanceof Class && ((Class) context).getGenericSuperclass() != null) {
                return makeInstantiatedType(type, ((Class) context).getGenericSuperclass());
            }
        } else if (gd instanceof Method) {
            return type;
        }
        logger.warning("Not found type variable " + tv + " in context " + context + " GenericDeclaration="
                + tv.getGenericDeclaration());
        // throw new InvalidKeyValuePropertyException("Not found type variable "+tv+" in context "+context);
        return type;
    }

    if (type instanceof WildcardType) {
        WildcardType wt = (WildcardType) type;
        Type[] upperBounds = new Type[wt.getUpperBounds().length];
        for (int i = 0; i < wt.getUpperBounds().length; i++) {
            upperBounds[i] = makeInstantiatedType(wt.getUpperBounds()[i], context);
        }
        Type[] lowerBounds = new Type[wt.getLowerBounds().length];
        for (int i = 0; i < wt.getLowerBounds().length; i++) {
            lowerBounds[i] = makeInstantiatedType(wt.getLowerBounds()[i], context);
        }
        return new WilcardTypeImpl(upperBounds, lowerBounds);
    }

    logger.warning("Unexpected " + type);
    return type;

}

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

/**
 * Returns class of TypeVariable.//from w w w.java  2 s . c o  m
 *
 * @param clazz
 * @param superClass
 * @param typeVariable
 * @param info
 * @return
 */
private static DeclaredType getDeclaredTypeVariableDeclared(final Class<?> clazz, final Class<?> superClass,
        final TypeVariable<?> typeVariable, final VariableInfo info) {
    if (clazz.equals(Object.class)) {
        return null;
    }

    if (typeVariable.getGenericDeclaration().equals(superClass)
            || typeVariable.getGenericDeclaration().equals(clazz)) {
        final int index = getIndexTypeVariable(typeVariable);
        if (typeVariable.getGenericDeclaration().equals(clazz)) {
            info.setIndex(index);
            info.setFirstClass((Class<?>) typeVariable.getGenericDeclaration());
            info.setInSuperclass(false);
            return null;
        } else {
            final ParameterizedType pType = (ParameterizedType) clazz.getGenericSuperclass();
            final Type type = pType.getActualTypeArguments()[index];
            if (type instanceof TypeVariable) {
                info.setIndex(getIndexTypeVariable((TypeVariable<?>) type));
                info.setFirstClass(clazz);
                info.setInSuperclass(true);
                return null;
            }
            return getDeclaredType(clazz, type);
        }
    } else {
        final DeclaredType declaredType = getDeclaredTypeVariableDeclared(clazz.getSuperclass(),
                superClass.getSuperclass(), typeVariable, info);
        if (declaredType == null) {
            ParameterizedType parameterizedType = null;
            if (clazz.getGenericSuperclass() instanceof ParameterizedType) {
                parameterizedType = (ParameterizedType) clazz.getGenericSuperclass();
                info.setInSuperclass(true);
                info.setFirstClass(clazz);
            } else {
                parameterizedType = (ParameterizedType) superClass.getGenericSuperclass();
                info.setInSuperclass(false);
                info.setFirstClass(superClass);
            }
            final Type type = parameterizedType.getActualTypeArguments()[info.getIndex()];
            if (type instanceof TypeVariable) {
                info.setIndex(getIndexTypeVariable((TypeVariable<?>) type));
                return null;
            }
            return getDeclaredType(clazz, type);
        } else {
            return declaredType;
        }
    }
}

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

/**
 * Returns position of TypeVariable in list of getTypeParameters on class.
 *
 * @param typeVariable/*from www  . j av a 2s .c o  m*/
 * @return
 */
private static int getIndexTypeVariable(final TypeVariable<?> typeVariable) {
    int index = -1;
    for (final TypeVariable<?> typeVariable2 : typeVariable.getGenericDeclaration().getTypeParameters()) {
        ++index;
        if (typeVariable.getName().equals(typeVariable2.getName())) {
            break;
        }
    }
    return index;
}