Example usage for java.lang.reflect TypeVariable getBounds

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

Introduction

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

Prototype

Type[] getBounds();

Source Link

Document

Returns an array of Type objects representing the upper bound(s) of this type variable.

Usage

From source file:com.expedia.tesla.compiler.plugins.JavaTypeMapper.java

private Type fromJava(Schema.SchemaBuilder schemaBuilder, java.lang.reflect.Type jt)
        throws TeslaSchemaException {
    if (jt instanceof java.lang.Class) {
        return fromJavaForward(schemaBuilder, (java.lang.Class<?>) jt);
    } else if (jt instanceof java.lang.reflect.WildcardType) {
        // ? extends Interface
        java.lang.reflect.WildcardType wt = (java.lang.reflect.WildcardType) jt;
        return fromJava(schemaBuilder, wt.getUpperBounds()[0]);
    } else if (jt instanceof java.lang.reflect.GenericArrayType) {
        // T[]/*from   w  w w.  j ava  2  s  . c  o  m*/
        java.lang.reflect.GenericArrayType ga = (java.lang.reflect.GenericArrayType) jt;
        Type elementType = fromJava(schemaBuilder, ga.getGenericComponentType());
        return schemaBuilder.addType(String.format("array<%s>", elementType.getTypeId()));
    } else if (jt instanceof TypeVariable) {
        // T
        TypeVariable<?> tv = (TypeVariable<?>) jt;
        return fromJava(schemaBuilder, tv.getBounds()[0]);
    } else if (jt instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) jt;
        java.lang.Class<?> rt = (java.lang.Class<?>) pt.getRawType();
        if (java.util.Map.class.isAssignableFrom(rt)) {
            // Map
            java.lang.reflect.Type kt = (java.lang.reflect.Type) pt.getActualTypeArguments()[0];
            java.lang.reflect.Type vt = (java.lang.reflect.Type) pt.getActualTypeArguments()[1];
            Type keyType = fromJava(schemaBuilder, kt);
            Type valueType = fromJava(schemaBuilder, vt);
            String fs = null;
            java.lang.Class<?> rawType = (java.lang.Class<?>) pt.getRawType();
            if (rawType.isInterface()) {
                fs = "map<%s,%s>";
            } else {
                fs = "map[" + rawType.getCanonicalName() + "]<%s,%s>";
            }
            String tid = String.format(fs, keyType.getTypeId(), valueType.getTypeId());
            return schemaBuilder.addType(tid);
        } else if (java.util.Collection.class.isAssignableFrom(rt)) {
            // Collection array (List<?>, Set<?>), use Collection and
            // ArrayList by default
            java.lang.reflect.Type et = (java.lang.reflect.Type) pt.getActualTypeArguments()[0];
            Type elementType = fromJava(schemaBuilder, et);
            String fs = null;
            java.lang.Class<?> rawType = (java.lang.Class<?>) pt.getRawType();
            if (rawType.isInterface()) {
                fs = "array[java.util.Collection,java.util.ArrayList]<%s>";
                if (java.util.List.class.isAssignableFrom(rt)) {
                    fs = "array[java.util.List,java.util.ArrayList]<%s>";
                } else if (java.util.Set.class.isAssignableFrom(rt)) {
                    fs = "array[java.util.Set,java.util.HashSet]<%s>";
                }
            } else {
                fs = "array[" + rawType.getCanonicalName() + "]<%s>";
            }
            String tid = String.format(fs, elementType.getTypeId());
            return schemaBuilder.addType(tid);
        }

        return fromJavaForward(schemaBuilder, rt);
    } else {
        throw new TeslaSchemaException("BUG");
    }
}

From source file:com.mobileman.kuravis.core.services.entity.impl.AbstractEntityServiceImpl.java

/**
 * /*from  w  ww.j av a  2  s. co m*/
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public AbstractEntityServiceImpl() {
    super();
    if (ParameterizedType.class.isInstance(getClass().getGenericSuperclass())) {
        java.lang.reflect.Type type = ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
        if (java.lang.reflect.TypeVariable.class.isInstance(type)) {
            TypeVariable typeVariable = TypeVariable.class.cast(type);
            this.entityClass = (Class<T>) typeVariable.getBounds()[0];
        } else {
            this.entityClass = (Class<T>) type;
        }
    } else {
        this.entityClass = null;
    }
}

From source file:com.datatorrent.stram.plan.logical.LogicalPlan.java

public static Type getPortType(Field f) {
    if (f.getGenericType() instanceof ParameterizedType) {
        ParameterizedType t = (ParameterizedType) f.getGenericType();
        //LOG.debug("Field type is parameterized: " + Arrays.asList(t.getActualTypeArguments()));
        //LOG.debug("rawType: " + t.getRawType()); // the port class
        Type typeArgument = t.getActualTypeArguments()[0];
        if (typeArgument instanceof Class) {
            return typeArgument;
        } else if (typeArgument instanceof TypeVariable) {
            TypeVariable<?> tv = (TypeVariable<?>) typeArgument;
            LOG.debug("bounds: " + Arrays.asList(tv.getBounds()));
            // variable may contain other variables, java.util.Map<java.lang.String, ? extends T2>
            return tv.getBounds()[0];
        } else if (typeArgument instanceof GenericArrayType) {
            LOG.debug("type {} is of GenericArrayType", typeArgument);
            return typeArgument;
        } else if (typeArgument instanceof WildcardType) {
            LOG.debug("type {} is of WildcardType", typeArgument);
            return typeArgument;
        } else if (typeArgument instanceof ParameterizedType) {
            return typeArgument;
        } else {/*from   ww w.  ja  va  2  s . c  o m*/
            LOG.error("Type argument is of expected type {}", typeArgument);
            return null;
        }
    } else {
        // ports are always parameterized
        LOG.error("No type variable: {}, typeParameters: {}", f.getType(),
                Arrays.asList(f.getClass().getTypeParameters()));
        return null;
    }
}

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

/**
 * <p>//from w  ww  .jav a  2 s. c  o m
 * Returns an array containing the sole type of {@link Object} if
 * {@link TypeVariable#getBounds()} returns an empty array. Otherwise, it
 * returns the result of <code>TypeVariable.getBounds()</code> passed into
 * {@link #normalizeUpperBounds}.
 * </p>
 * 
 * @param typeVariable
 *            the subject type variable
 * @return a non-empty array containing the bounds of the type variable.
 */
public static Type[] getImplicitBounds(TypeVariable<?> typeVariable) {
    Type[] bounds = typeVariable.getBounds();

    return bounds.length == 0 ? new Type[] { Object.class } : normalizeUpperBounds(bounds);
}

From source file:org.alfresco.module.org_alfresco_module_rm.api.PublicAPITestUtil.java

/**
 * Find all classes that are within the supplied type. For example a {@code Pair<Set<String>, Integer>} contains
 * references to four classes.//ww w .j  av a2s  .c  o  m
 *
 * @param type The type to examine.
 * @param processedTypes The set of types which have already been processed. If {@code type} is within this set then
 *            the method returns an empty set, to prevent analysis of the same type multiple times, and to guard
 *            against circular references. The underlying set is updated with the given type.
 * @return The set of classes used to form the given type.
 */
private static Set<Class<?>> getClassesFromType(Type type, Set<Type> processedTypes) {
    Set<Class<?>> returnClasses = new HashSet<>();

    if (processedTypes.add(type)) {
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            returnClasses.add((Class<?>) parameterizedType.getRawType());

            for (Type t : parameterizedType.getActualTypeArguments()) {
                returnClasses.addAll(getClassesFromType(t, processedTypes));
            }
        } else if (type instanceof Class) {
            Class<?> clazz = (Class<?>) type;
            if (clazz.isArray()) {
                returnClasses.add(clazz.getComponentType());
            }
            returnClasses.add(clazz);
        } else if (type instanceof WildcardType) {
            // No-op - Caller can choose what type to use.
        } else if (type instanceof TypeVariable<?>) {
            TypeVariable<?> typeVariable = (TypeVariable<?>) type;
            for (Type bound : typeVariable.getBounds()) {
                returnClasses.addAll(getClassesFromType(bound, processedTypes));
            }
        } else if (type instanceof GenericArrayType) {
            GenericArrayType genericArrayType = (GenericArrayType) type;
            returnClasses
                    .addAll(getClassesFromType(genericArrayType.getGenericComponentType(), processedTypes));
        } else {
            throw new IllegalStateException("This test was not written to work with type " + type);
        }
    }
    return returnClasses;
}

From source file:org.assertj.assertions.generator.util.ClassUtil.java

/**
 * Get the underlying class for a type, or null if the type is a variable type.
 *
 * @param type the type/*from   ww w.ja v a 2 s.  c  o  m*/
 * @return the underlying class
 */
public static Class<?> getClass(final Type type) {
    if (type instanceof Class)
        return (Class<?>) type;
    if (type instanceof ParameterizedType)
        return getClass(((ParameterizedType) type).getRawType());

    if (type instanceof GenericArrayType) {
        final Type componentType = ((GenericArrayType) type).getGenericComponentType();
        final Class<?> componentClass = getClass(componentType);
        return componentClass == null ? null : Array.newInstance(componentClass, 0).getClass();
    } else if (type instanceof WildcardType) {
        final WildcardType wildcardType = (WildcardType) type;
        return wildcardType.getUpperBounds() != null ? getClass(wildcardType.getUpperBounds()[0])
                : wildcardType.getLowerBounds() != null ? getClass(wildcardType.getLowerBounds()[0]) : null;
    } else if (type instanceof TypeVariable) {
        final TypeVariable<?> typeVariable = (TypeVariable<?>) type;
        final Type[] bounds = typeVariable.getBounds();
        return bounds.length > 0 ? getClass(bounds[0]) : Object.class;
    }
    return null;
}

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

/**
 * Set type parameters based on return type
 * /*w ww  .  ja v a2  s. c om*/
 * @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.GenericClass.java

/**
 * Returns the erasure of the given type.
 *///  w  ww . j av a  2  s.  com
private static Class<?> erase(Type type) {
    if (type instanceof Class) {
        return (Class<?>) type;
    } else if (type instanceof ParameterizedType) {
        return (Class<?>) ((ParameterizedType) type).getRawType();
    } else if (type instanceof TypeVariable) {
        TypeVariable<?> tv = (TypeVariable<?>) type;
        if (tv.getBounds().length == 0)
            return Object.class;
        else
            return erase(tv.getBounds()[0]);
    } else if (type instanceof GenericArrayType) {
        GenericArrayType aType = (GenericArrayType) type;
        return GenericArrayTypeImpl.createArrayType(erase(aType.getGenericComponentType()));
    } else if (type instanceof CaptureType) {
        CaptureType captureType = (CaptureType) type;
        if (captureType.getUpperBounds().length == 0)
            return Object.class;
        else
            return erase(captureType.getUpperBounds()[0]);
    } else {
        // TODO at least support CaptureType here
        throw new RuntimeException("not supported: " + type.getClass());
    }
}

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

private void getGenericParameterizedTypeBounds(Collection<GenericClass> bounds) {
    for (TypeVariable<?> typeVar : getTypeVariables()) {
        for (Type t : typeVar.getBounds()) {
            bounds.add(new GenericClass(t));
        }/*ww  w  .  j  av  a 2s .c  o  m*/
    }
}

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

/**
 * Determine whether the boundaries of the type variable are satisfied by
 * this class//from w  w  w .j  av  a  2 s .c om
 * 
 * @param typeVariable
 * @return
 */
public boolean satisfiesBoundaries(TypeVariable<?> typeVariable, Map<TypeVariable<?>, Type> typeMap) {
    boolean isAssignable = true;
    // logger.debug("Checking class: " + type + " against type variable " + typeVariable+" with map "+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: "+var+" of "+var.getGenericDeclaration());
            if (ownerVariableMap.get(var) instanceof TypeVariable<?>) {
                //logger.debug("Is set to type var: "+ownerVariableMap.get(var)+" of "+((TypeVariable<?>)ownerVariableMap.get(var)).getGenericDeclaration());
                TypeVariable<?> value = (TypeVariable<?>) ownerVariableMap.get(var);
                if (ownerVariableMap.containsKey(value)) {
                    Type other = ownerVariableMap.get(value);
                    if (var != other && value != other) {
                        //logger.debug("Replacing "+var+" with "+other);
                        ownerVariableMap.put(var, other);
                        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 " + toString() + " is an enum!");

                continue;
            } else {
                // If it's not an enum, it cannot be assignable to enum!
                //logger.debug("Class " + toString() + " is not an enum.");
                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) && !(boundType instanceof WildcardType)) {
            //logger.debug("Not assignable: " + type + " and " + 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: " + boundType + " and "
                    //        + instanceType);
                }
            }
            isAssignable = false;
            break;
        }
    }
    //logger.debug("Result: is assignable " + isAssignable);
    return isAssignable;
}