Example usage for java.lang.reflect WildcardType getLowerBounds

List of usage examples for java.lang.reflect WildcardType getLowerBounds

Introduction

In this page you can find the example usage for java.lang.reflect WildcardType getLowerBounds.

Prototype

Type[] getLowerBounds();

Source Link

Document

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

Usage

From source file:io.neba.core.util.ReflectionUtil.java

/**
 * Resolves the generic type of a {@link Collection} from a {@link Field}, e.g.
 *
 * <pre>//from   ww w .jav  a2  s.  c  o  m
 * private List&lt;MyModel&gt; myModel -&gt; MyModel.
 * </pre>
 *
 * @param field must not be <code>null</code>.
 * @return never null.
 */
public static Class<?> getCollectionComponentType(Class<?> definingType, Field field) {
    if (field == null) {
        throw new IllegalArgumentException("Method parameter field must not be null.");
    }

    // The generic type may contain the generic type declarations, e.g. List<String>.
    Type type = field.getGenericType();
    if (!(type instanceof ParameterizedType)) {
        throw new IllegalArgumentException("Cannot obtain the component type of " + field
                + ", it does not declare generic type parameters.");
    }

    // Only the ParametrizedType contains reflection information about the actual type.
    ParameterizedType parameterizedType = (ParameterizedType) type;

    Type[] typeArguments = parameterizedType.getActualTypeArguments();

    // We expect exactly one argument representing the model type.
    if (typeArguments.length != 1) {
        signalUnsupportedNumberOfTypeDeclarations(field);
    }

    Type componentType = typeArguments[0];

    // Wildcard type <X ... Y>
    if (componentType instanceof WildcardType) {
        WildcardType wildcardType = (WildcardType) componentType;
        Type[] lowerBounds = wildcardType.getLowerBounds();
        if (lowerBounds.length == 0) {
            throw new IllegalArgumentException("Cannot obtain the component type of " + field
                    + ", it has a wildcard declaration with an upper"
                    + " bound (<? extends Y>) and is thus read-only."
                    + " Only simple type parameters (e.g. List<MyType>)"
                    + " or lower bound wildcards (e.g. List<? super MyModel>)" + " are supported.");
        }
        componentType = lowerBounds[0];
    }

    return getRawType(componentType, definingType);
}

From source file:com.autentia.common.util.ClassWithList.java

private static void print(WildcardType wt) {
    System.out.println("Wildcard type");
    System.out.println("Lower bounds:");
    for (Type b : wt.getLowerBounds()) {
        print(b);//from   www. j  a v  a2  s  .  c  om
    }

    System.out.println("Upper bounds:");
    for (Type b : wt.getUpperBounds()) {
        print(b);
    }
}

From source file:TypeUtils.java

private static boolean isAssignable(WildcardType lhsType, Type rhsType) {
    Type[] upperBounds = lhsType.getUpperBounds();
    Type[] lowerBounds = lhsType.getLowerBounds();
    for (int size = upperBounds.length, i = 0; i < size; ++i) {
        if (!isAssignable(upperBounds[i], rhsType)) {
            return false;
        }//from  w w  w .jav a 2  s  .  c  om
    }
    for (int size = lowerBounds.length, i = 0; i < size; ++i) {
        if (!isAssignable(rhsType, lowerBounds[i])) {
            return false;
        }
    }
    return true;
}

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

/**
 * <p>/*from   ww  w .j a  v  a2  s.  com*/
 * Returns an array containing a single value of <code>null</code> if
 * {@link WildcardType#getLowerBounds()} returns an empty array. Otherwise,
 * it returns the result of <code>WildcardType.getLowerBounds()</code>.
 * </p>
 * 
 * @param wildcardType
 *            the subject wildcard type
 * @return a non-empty array containing the lower bounds of the wildcard
 *         type.
 */
public static Type[] getImplicitLowerBounds(WildcardType wildcardType) {
    Type[] bounds = wildcardType.getLowerBounds();

    return bounds.length == 0 ? new Type[] { null } : bounds;
}

From source file:org.apache.sling.stanbol.rest.ported.JerseyUtils.java

/**
 * Tests if a generic type (may be &lt;?&gt;, &lt;? extends {required}&gt; 
 * or &lt;? super {required}&gt;) is compatible with the required one.
 * TODO: Should be moved to an utility class
 * @param required the required class the generic type MUST BE compatible with
 * @param genericType the required class
 * @return if the generic type is compatible with the required class
 *//*from ww w. j a  va2s  .c  o m*/
public static boolean testType(Class<?> required, Type genericType) {
    //for the examples let assume that a Set is the raw type and the
    //requested generic type is a Representation with the following class
    //hierarchy:
    // Object
    //     -> Representation
    //         -> RdfRepresentation
    //         -> InMemoryRepresentation
    //     -> InputStream
    //     -> Collection<T>
    boolean typeOK;
    if (genericType instanceof Class<?>) {
        //OK
        //  Set<Representation>
        //  Set<Object>
        //NOT OK
        //  Set<RdfRepresentation>
        //  Set<InputStream>
        typeOK = ((Class<?>) genericType).isAssignableFrom(required);
    } else if (genericType instanceof WildcardType) {
        //In cases <? super {class}>, <? extends {class}, <?>
        WildcardType wildcardSetType = (WildcardType) genericType;
        if (wildcardSetType.getLowerBounds().length > 0) {
            Type lowerBound = wildcardSetType.getLowerBounds()[0];
            //OK
            //  Set<? super RdfRepresentation>
            //  Set<? super Representation>
            //NOT OK
            //  Set<? super InputStream>
            //  Set<? super Collection<Representation>>
            typeOK = lowerBound instanceof Class<?> && required.isAssignableFrom((Class<?>) lowerBound);
        } else if (wildcardSetType.getUpperBounds().length > 0) {
            Type upperBound = wildcardSetType.getUpperBounds()[0];
            //OK
            //  Set<? extends Representation>
            //  Set<? extends Object>
            //NOT OK
            //  Set<? extends RdfRepresentation>
            //  Set<? extends InputStream>
            //  Set<? extends Collection<Representation>
            typeOK = upperBound instanceof Class<?> && ((Class<?>) upperBound).isAssignableFrom(required);
        } else { //no upper nor lower bound
            // Set<?>
            typeOK = true;
        }
    } else if (required.isArray() && genericType instanceof GenericArrayType) {
        //In case the required type is an array we need also to support 
        //possible generic Array specifications
        GenericArrayType arrayType = (GenericArrayType) genericType;
        typeOK = testType(required.getComponentType(), arrayType.getGenericComponentType());
    } else {
        //GenericArrayType but !required.isArray() -> incompatible
        //TypeVariable -> no variables define -> incompatible
        typeOK = false;
    }
    return typeOK;
}

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/* w  w w. j ava2 s  .c om*/
 * @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.datalorax.populace.core.util.TypeResolver.java

private Type resolveWildcard(final WildcardType type, final TypeToken<?> assigningType) {
    final Type[] lowerBounds = type.getLowerBounds();
    if (lowerBounds.length != 0) {
        final Type[] resolvedLowerBounds = resolve(lowerBounds, assigningType);
        if (Arrays.equals(resolvedLowerBounds, lowerBounds)) {
            return type;
        }/*from  w  w w .ja v  a2s.c  o m*/

        return TypeUtils.wildcardTypeWithLowerBounds(resolvedLowerBounds);
    }

    final Type[] resolvedUpperBounds = resolve(type.getUpperBounds(), assigningType);
    if (Arrays.equals(resolvedUpperBounds, type.getUpperBounds())) {
        return type;
    }

    return TypeUtils.wildcardTypeWithUpperBounds(resolvedUpperBounds);
}

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

private static Type ensureConsistentWildcard(final WildcardType type) {
    final Type[] lowerBounds = Arrays.stream(type.getLowerBounds()).map(TypeUtils::ensureConsistentType)
            .toArray(Type[]::new);
    final Type[] upperBounds = Arrays.stream(type.getUpperBounds()).map(TypeUtils::ensureConsistentType)
            .toArray(Type[]::new);
    return org.apache.commons.lang3.reflect.TypeUtils.wildcardType().withLowerBounds(lowerBounds)
            .withUpperBounds(upperBounds).build();
}

From source file:org.diorite.cfg.system.ConfigField.java

public static void getAllPossibleTypes(final Set<Class<?>> classes, final Set<Type> checkedTypes,
        final Type rawType) {
    if (!checkedTypes.add(rawType)) {
        return;// ww  w . j av a2  s.co m
    }
    if (rawType instanceof Class) {
        classes.add((Class<?>) rawType);
    }
    if (rawType instanceof WildcardType) {
        final WildcardType type = (WildcardType) rawType;
        for (final Type t : type.getLowerBounds()) {
            getAllPossibleTypes(classes, checkedTypes, t);
        }
        for (final Type t : type.getUpperBounds()) {
            getAllPossibleTypes(classes, checkedTypes, t);
        }
    }
    if (rawType instanceof GenericArrayType) {
        getAllPossibleTypes(classes, checkedTypes, ((GenericArrayType) rawType).getGenericComponentType());
    }
    if (rawType instanceof TypeVariable) {
        final TypeVariable<?> type = (TypeVariable<?>) rawType;
        for (final Type t : type.getBounds()) {
            getAllPossibleTypes(classes, checkedTypes, t);
        }
    }
    if (rawType instanceof ParameterizedType) {
        final ParameterizedType type = (ParameterizedType) rawType;
        getAllPossibleTypes(classes, checkedTypes, type.getRawType());
        getAllPossibleTypes(classes, checkedTypes, type.getOwnerType());
        for (final Type t : type.getActualTypeArguments()) {
            getAllPossibleTypes(classes, checkedTypes, t);
        }
    }
}

From source file:org.eclipse.wb.internal.swing.databinding.model.generic.GenericUtils.java

private static IGenericType resolveType(Type type) {
    if (type instanceof Class<?>) {
        return new ClassGenericType((Class<?>) type, null, null);
    }/* ww w  .j  a va2 s  .c o  m*/
    if (type instanceof WildcardType) {
        WildcardType wildcardType = (WildcardType) type;
        if (ArrayUtils.isEmpty(wildcardType.getUpperBounds())
                && ArrayUtils.isEmpty(wildcardType.getLowerBounds())) {
            return ClassGenericType.WILDCARD;
        }
    }
    if (type instanceof ParameterizedType || type instanceof GenericArrayType || type instanceof WildcardType) {
        return new ClassGenericType(null, resolveTypeName(type), "???");
    }
    if (type instanceof TypeVariable<?>) {
        return ClassGenericType.WILDCARD;
    }
    Assert.fail(MessageFormat.format("Undefine type: {0}", type));
    return null;
}