Example usage for org.apache.commons.lang3.reflect TypeUtils getTypeArguments

List of usage examples for org.apache.commons.lang3.reflect TypeUtils getTypeArguments

Introduction

In this page you can find the example usage for org.apache.commons.lang3.reflect TypeUtils getTypeArguments.

Prototype

public static Map<TypeVariable<?>, Type> getTypeArguments(final Type type, final Class<?> toClass) 

Source Link

Document

Gets the type arguments of a class/interface based on a subtype.

Usage

From source file:com.savoirtech.eos.util.TypeVariableUtils.java

@SuppressWarnings("unchecked")
public static <T, C extends Type> C getTypeVariableBinding(Class<T> concreteClass,
        Class<? super T> definingClass, int varIndex) {
    final Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(concreteClass, definingClass);
    TypeVariable<? extends Class<? super T>> entityTypeVar = definingClass.getTypeParameters()[varIndex];
    return (C) typeArguments.get(entityTypeVar);
}

From source file:com.meltmedia.cadmium.core.commands.CommandInspectionTest.java

/**
 * Tests the use of TypeUtils.getTypeArguments to lookup the type assigned to a generic.
 *///w  ww.j av  a  2  s. com
@Test
public void testTypeUtilsGetTypeArguments() {
    Class<?> commandClass = new HistoryRequestCommandAction().getClass();
    Map<TypeVariable<?>, Type> genericMap = TypeUtils.getTypeArguments(commandClass, CommandAction.class);
    assertNotNull("The generic map was null.", genericMap);
    assertEquals("The genric map has an unexpected number of entries.", 1, genericMap.entrySet().size());
    TypeVariable<?> parameterVariable = CommandAction.class.getTypeParameters()[0];
    assertNotNull("The parameter variable from command action is null.", parameterVariable);
    Type bodyType = genericMap.get(parameterVariable);
    assertEquals("The type for history request was wrong.", HistoryRequest.class, bodyType);
}

From source file:com.meltmedia.cadmium.core.commands.CommandBodyMapProvider.java

@Inject
public CommandBodyMapProvider(Set<CommandAction<?>> commandSet) {
    for (CommandAction<?> command : commandSet) {
        Map<TypeVariable<?>, Type> genericMap = TypeUtils.getTypeArguments(command.getClass(),
                CommandAction.class);
        Type bodyType = genericMap.get(CommandAction.class.getTypeParameters()[0]);
        if (bodyType instanceof Class<?>)
            bodyTypeMap.put(command.getName(), (Class<?>) bodyType);
        else {//from  w  ww  .j  av a 2s.  c o m
            log.error("Could not identify message body type for command {}:{}.", command.getName(),
                    command.getClass().getName());
        }
    }
}

From source file:cz.jirutka.commons.persistence.dao.DelegatingSpecificDAO.java

private Class<E> determineEntityClass() {
    TypeVariable<?> typeVarE = DelegatingSpecificDAO.class.getTypeParameters()[0];
    Type implType = this.getClass();

    return (Class<E>) TypeUtils.getTypeArguments(implType, DelegatingSpecificDAO.class).get(typeVarE);
}

From source file:org.apache.bval.jsr.ConstraintValidation.java

private static <A extends Annotation> Map<Type, Collection<Class<? extends ConstraintValidator<A, ?>>>> getValidatorsTypes(
        Class<? extends ConstraintValidator<A, ?>>[] constraintValidatorClasses) {
    final Map<Type, Collection<Class<? extends ConstraintValidator<A, ?>>>> validatorsTypes = new HashMap<Type, Collection<Class<? extends ConstraintValidator<A, ?>>>>();
    for (Class<? extends ConstraintValidator<A, ?>> validatorType : constraintValidatorClasses) {
        Type validatedType = TypeUtils.getTypeArguments(validatorType, ConstraintValidator.class)
                .get(ConstraintValidator.class.getTypeParameters()[1]);
        if (validatedType == null) {
            throw new ValidationException(
                    String.format("Could not detect validated type for %s", validatorType));
        }//  w w  w  .ja va  2s.co m
        if (validatedType instanceof GenericArrayType) {
            final Type componentType = TypeUtils.getArrayComponentType(validatedType);
            if (componentType instanceof Class<?>) {
                validatedType = Array.newInstance((Class<?>) componentType, 0).getClass();
            }
        }
        if (!validatorsTypes.containsKey(validatedType)) {
            validatorsTypes.put(validatedType, new ArrayList<Class<? extends ConstraintValidator<A, ?>>>());
        }
        validatorsTypes.get(validatedType).add(validatorType);
    }
    return validatorsTypes;
}

From source file:org.apache.bval.util.IndexedAccess.java

/**
 * Get the Java element type of a particular container type.
 * //from   w ww .j a v a  2s  .com
 * @param containerType
 * @return Type or <code>null</code> if <code>containerType</code> is not
 *         some type of {@link Iterable} or array
 */
public static Type getJavaElementType(Type containerType) {
    if (TypeUtils.isArrayType(containerType)) {
        return TypeUtils.getArrayComponentType(containerType);
    }
    if (TypeUtils.isAssignable(containerType, Iterable.class)) {
        Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(containerType, Iterable.class);
        return ObjectUtils.defaultIfNull(TypeUtils.unrollVariables(typeArguments, ITERABLE_TYPE), Object.class);
    }
    return null;
}

From source file:org.apache.bval.util.KeyedAccess.java

/**
 * Get the Java element type of a particular container type.
 * //from w  w w  .j av a  2 s  .co  m
 * @param containerType
 * @return Type or <code>null</code> if <code>containerType</code> is not
 *         some kind of {@link Map}
 */
public static Type getJavaElementType(Type containerType) {
    if (TypeUtils.isAssignable(containerType, Map.class)) {
        Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(containerType, Map.class);
        return ObjectUtils.defaultIfNull(TypeUtils.unrollVariables(typeArguments, MAP_TYPEVARS[1]),
                Object.class);
    }
    return null;
}

From source file:org.apache.bval.util.KeyedAccess.java

/**
 * {@inheritDoc}//from w w  w .jav a 2  s.  co m
 */
@Override
public Object get(Object instance) {
    if (instance instanceof Map<?, ?>) {
        Map<?, ?> map = (Map<?, ?>) instance;
        Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(containerType, Map.class);
        Type keyType = TypeUtils.unrollVariables(typeArguments, MAP_TYPEVARS[0]);
        if (key == null || keyType == null || TypeUtils.isInstance(key, keyType)) {
            return map.get(key);
        }
        if (key instanceof String) {
            String name = (String) key;
            Class<?> rawKeyType = TypeUtils.getRawType(keyType, containerType);
            if (rawKeyType.isEnum()) {
                @SuppressWarnings({ "unchecked", "rawtypes" })
                final Object result = map.get(Enum.valueOf((Class<? extends Enum>) rawKeyType, name));
                return result;
            }
            for (Map.Entry<?, ?> e : map.entrySet()) {
                if (name.equals(e.getKey())) {
                    return e.getValue();
                }
            }
        }
    }
    return null;
}

From source file:org.apache.sling.validation.impl.util.ValidatorTypeUtil.java

/**
 * /*ww  w  . j  a  va  2s .co m*/
 * @param validator
 * @return the type parametrization value on the {@link Validator} interface
 */
public static @Nonnull Class<?> getValidatorType(Validator<?> validator) {
    // get all type arguments from the current validator class up to the Validator interface
    Map<TypeVariable<?>, java.lang.reflect.Type> typeMap = TypeUtils.getTypeArguments(validator.getClass(),
            Validator.class);
    java.lang.reflect.Type type = null;
    for (Entry<TypeVariable<?>, java.lang.reflect.Type> entry : typeMap.entrySet()) {
        type = entry.getValue();
        // check if this is really the type argument defined on the interface {@link Validator}
        if (entry.getKey().getGenericDeclaration() instanceof Class<?>) {
            Class<?> clazz = (Class<?>) entry.getKey().getGenericDeclaration();
            if (clazz.equals(Validator.class)) {
                // Java6 doesn't return the class for array types due to this bug: http://bugs.java.com/view_bug.do?bug_id=5041784
                if (type instanceof GenericArrayType) {
                    // as a workaround make a new array class out of the generic component type encapsulated in the generic array type
                    type = Array.newInstance((Class<?>) ((GenericArrayType) type).getGenericComponentType(), 0)
                            .getClass();
                }
                if (type instanceof Class<?>) {
                    return (Class<?>) type;
                }
                // type may also be a parameterized type (e.g. for Collection<String>), this is not allowed!
                else {
                    throw new IllegalArgumentException(
                            "Validators may not use parameterized types as type parameter. Only simple class types and arrays of class types are allowed.");
                }
            }
        }

    }
    throw new IllegalArgumentException("Validator '" + validator + "' has not valid type parameter!");
}

From source file:org.grouplens.grapht.util.Types.java

/**
 * Get the type that is provided by a given implementation of
 * {@link Provider}./*  w  ww  .  j  a va 2s  .c om*/
 * 
 * @param providerClass The provider's class
 * @return The provided class type
 * @throws IllegalArgumentException if the class doesn't actually implement
 *             Provider
 */
public static Class<?> getProvidedType(Class<? extends Provider<?>> providerClass) {
    com.google.common.base.Preconditions.checkArgument(Provider.class.isAssignableFrom(providerClass),
            "class is not Provider class");
    Map<TypeVariable<?>, Type> bindings = TypeUtils.getTypeArguments(providerClass, Provider.class);
    Type boundType = bindings.get(PROVIDER_TYPE_VAR);

    if (boundType == null || boundType instanceof TypeVariable) {
        throw new IllegalArgumentException("Class provided by " + providerClass.getName() + " is generic");
    }
    final Class<?> inferredType = TypeUtils.getRawType(bindings.get(PROVIDER_TYPE_VAR), null);
    try {
        final Class<?> observedType = providerClass.getMethod("get").getReturnType();
        if (inferredType != null && inferredType.isAssignableFrom(observedType)) {
            return observedType;
        } else {
            return inferredType;
        }
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("Class does not implement get()", e);
    }
}