Example usage for java.lang.reflect ParameterizedType getActualTypeArguments

List of usage examples for java.lang.reflect ParameterizedType getActualTypeArguments

Introduction

In this page you can find the example usage for java.lang.reflect ParameterizedType getActualTypeArguments.

Prototype

Type[] getActualTypeArguments();

Source Link

Document

Returns an array of Type objects representing the actual type arguments to this type.

Usage

From source file:io.werval.runtime.util.TypeResolver.java

/**
 * Populates the {@code typeVariableMap} with type arguments and parameters for the given {@code type}.
 *///w  w  w.j  av  a  2 s. c  o  m
private static void buildTypeVariableMap(ParameterizedType type, Map<TypeVariable<?>, Type> typeVariableMap) {
    if (type.getRawType() instanceof Class) {
        TypeVariable<?>[] typeVariables = ((Class<?>) type.getRawType()).getTypeParameters();
        Type[] typeArguments = type.getActualTypeArguments();

        for (int i = 0; i < typeArguments.length; i++) {
            TypeVariable<?> variable = typeVariables[i];
            Type typeArgument = typeArguments[i];

            if (typeArgument instanceof Class) {
                typeVariableMap.put(variable, typeArgument);
            } else if (typeArgument instanceof GenericArrayType) {
                typeVariableMap.put(variable, typeArgument);
            } else if (typeArgument instanceof ParameterizedType) {
                typeVariableMap.put(variable, typeArgument);
            } else if (typeArgument instanceof TypeVariable) {
                TypeVariable<?> typeVariableArgument = (TypeVariable<?>) typeArgument;
                Type resolvedType = typeVariableMap.get(typeVariableArgument);
                if (resolvedType == null) {
                    resolvedType = resolveBound(typeVariableArgument);
                }
                typeVariableMap.put(variable, resolvedType);
            }
        }
    }
}

From source file:org.brekka.stillingar.spring.bpp.ConfigurationBeanPostProcessor.java

/**
 * Identifies the type of the parameterised list.
 * //from www . j  a v  a 2 s.com
 * @param listType
 *            the list type to inspect
 * @return the list type or null if it is not parameterised.
 */
@SuppressWarnings("rawtypes")
private static Class<?> listType(Type listType) {
    Class<?> type;
    if (listType instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) listType;
        Type[] actualTypeArguments = pType.getActualTypeArguments();
        type = (Class) actualTypeArguments[0];
    } else {
        throw new ConfigurationException(String.format("Not a parameterised list type: '%s'", listType));
    }
    return type;
}

From source file:es.logongas.ix3.util.ReflectionUtil.java

public static boolean isFieldParametrizedMap(Field field, Class keyClass, Class valueClass) {
    Type type = field.getGenericType();

    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        if (parameterizedType.getRawType().equals(Map.class)) {
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();

            if ((actualTypeArguments == null) || (actualTypeArguments.length != 2)) {
                return false;
            } else {
                if ((actualTypeArguments[0].equals(keyClass)) && (actualTypeArguments[1].equals(valueClass))) {
                    return true;
                } else {
                    return false;
                }//from  w  w  w . j  a va  2  s .  c  o  m
            }

        } else {
            return false;
        }

    } else {
        return false;
    }
}

From source file:es.logongas.ix3.util.ReflectionUtil.java

public static boolean isFieldParametrizedList(Field field, Class listClass) {
    Type type = field.getGenericType();

    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        if (parameterizedType.getRawType().equals(List.class)) {
            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();

            if ((actualTypeArguments == null) || (actualTypeArguments.length != 1)) {
                return false;
            } else {
                if (actualTypeArguments[0].equals(listClass)) {
                    return true;
                } else {
                    return false;
                }// w w  w.j a va  2s .  c o  m
            }

        } else {
            return false;
        }

    } else {
        return false;
    }
}

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

public static Type replaceTypeVariable(Type targetType, TypeVariable<?> variable, Type variableType) {
    if (targetType instanceof Class<?>)
        return targetType;
    else if (targetType instanceof GenericArrayType) {
        GenericArrayType gType = (GenericArrayType) targetType;
        Type componentType = replaceTypeVariable(gType.getGenericComponentType(), variable, variableType);
        return GenericArrayTypeImpl.createArrayType(componentType);

    } else if (targetType instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) targetType;
        Type ownerType = null;//from w ww.  ja  va2  s  .  c  o  m
        if (pType.getOwnerType() != null) {
            ownerType = replaceTypeVariable(pType.getOwnerType(), variable, variableType);
        }
        Type[] originalParameterTypes = pType.getActualTypeArguments();
        Type[] parameterTypes = new Type[originalParameterTypes.length];
        for (int i = 0; i < originalParameterTypes.length; i++) {
            parameterTypes[i] = replaceTypeVariable(originalParameterTypes[i], variable, variableType);
        }

        /*
        if (variableType instanceof ParameterizedType) {
           ParameterizedType parameterizedVars = (ParameterizedType) variableType;
           Map<TypeVariable<?>, Type> subTypes = TypeUtils.getTypeArguments(parameterizedVars);
           for (Entry<TypeVariable<?>, Type> subTypeEntry : subTypes.entrySet()) {
              if (pType.getOwnerType() != null) {
          ownerType = replaceTypeVariable(pType.getOwnerType(),
                                          subTypeEntry.getKey(),
                                          subTypeEntry.getValue());
              }
              for (int i = 0; i < originalParameterTypes.length; i++) {
          parameterTypes[i] = replaceTypeVariable(originalParameterTypes[i],
                                                  subTypeEntry.getKey(),
                                                  subTypeEntry.getValue());
              }
                
           }
        }
        */

        return new ParameterizedTypeImpl((Class<?>) pType.getRawType(), parameterTypes, ownerType);

    } else if (targetType instanceof WildcardType) {
        WildcardType wType = (WildcardType) targetType;
        Type[] originalUpperBounds = wType.getUpperBounds();
        Type[] originalLowerBounds = wType.getLowerBounds();
        Type[] upperBounds = new Type[originalUpperBounds.length];
        Type[] lowerBounds = new Type[originalLowerBounds.length];

        for (int i = 0; i < originalUpperBounds.length; i++) {
            upperBounds[i] = replaceTypeVariable(originalUpperBounds[i], variable, variableType);
        }
        for (int i = 0; i < originalLowerBounds.length; i++) {
            lowerBounds[i] = replaceTypeVariable(originalLowerBounds[i], variable, variableType);
        }

        return new WildcardTypeImpl(upperBounds, lowerBounds);
    } else if (targetType instanceof TypeVariable<?>) {
        if (targetType.equals(variable)) {
            //logger.debug("Do equal: " + variable + "/" + targetType);
            return variableType;
        } else {
            //logger.debug("Do not equal: " + variable + "/" + targetType);
            //logger.debug("Do not equal: " + variable.getGenericDeclaration() + "/"
            //        + ((TypeVariable<?>) targetType).getGenericDeclaration());
            return targetType;
        }
    } else {
        //logger.debug("Unknown type of class " + targetType.getClass() + ": "
        //        + targetType);
        return targetType;
    }
}

From source file:com.frame.base.utils.ReflectionUtils.java

/**
 * Get the actual type arguments a child class has used to extend a generic
 * base class. (Taken from http://www.artima.com/weblogs/viewpost.jsp?thread=208860. Thanks
 * mathieu.grenonville for finding this solution!)
 * //from  w  w w . jav a 2s .c o  m
 * @param baseClass
 *            the base class
 * @param childClass
 *            the child class
 * @return a list of the raw classes for the actual type arguments.
 */
@SuppressWarnings("rawtypes")
public static <T> List<Class<?>> getTypeArguments(Class<T> baseClass, Class<? extends T> childClass) {
    Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
    Type type = childClass;
    // start walking up the inheritance hierarchy until we hit baseClass
    while (!getClass(type).equals(baseClass)) {
        if (type instanceof Class) {
            // there is no useful information for us in raw types, so just
            // keep going.
            type = ((Class) type).getGenericSuperclass();
        } else {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            Class<?> rawType = (Class) parameterizedType.getRawType();

            Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
            for (int i = 0; i < actualTypeArguments.length; i++) {
                resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
            }

            if (!rawType.equals(baseClass)) {
                type = rawType.getGenericSuperclass();
            }
        }
    }

    // finally, for each actual type argument provided to baseClass,
    // determine (if possible)
    // the raw class for that type argument.
    Type[] actualTypeArguments;
    if (type instanceof Class) {
        actualTypeArguments = ((Class) type).getTypeParameters();
    } else {
        actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
    }
    List<Class<?>> typeArgumentsAsClasses = new ArrayList<Class<?>>();
    // resolve types by chasing down type variables.
    for (Type baseType : actualTypeArguments) {
        while (resolvedTypes.containsKey(baseType)) {
            baseType = resolvedTypes.get(baseType);
        }
        typeArgumentsAsClasses.add(getClass(baseType));
    }
    return typeArgumentsAsClasses;
}

From source file:ReflectUtil.java

/**
 * Returns an array of Type objects representing the actual type arguments
 * to targetType used by clazz./*from w w w.  j  a  v a  2s  .c om*/
 * 
 * @param clazz the implementing class (or subclass)
 * @param targetType the implemented generic class or interface
 * @return an array of Type objects or null
 */
public static Type[] getActualTypeArguments(Class<?> clazz, Class<?> targetType) {
    Set<Class<?>> classes = new HashSet<Class<?>>();
    classes.add(clazz);

    if (targetType.isInterface())
        classes.addAll(getImplementedInterfaces(clazz));

    Class<?> superClass = clazz.getSuperclass();
    while (superClass != null) {
        classes.add(superClass);
        superClass = superClass.getSuperclass();
    }

    for (Class<?> search : classes) {
        for (Type type : (targetType.isInterface() ? search.getGenericInterfaces()
                : new Type[] { search.getGenericSuperclass() })) {
            if (type instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                if (targetType.equals(parameterizedType.getRawType()))
                    return parameterizedType.getActualTypeArguments();
            }
        }
    }

    return null;
}

From source file:com.github.gekoh.yagen.util.MappingUtils.java

public static Class determineTargetEntity(AccessibleObject ao, Class<?> specifiedTargetEntity) {
    String errorMessage = "targetEntity not present and not determinable (need generic declaration)";
    try {//from www.  j a  v  a 2 s  . co  m
        if (specifiedTargetEntity != null && specifiedTargetEntity != Void.TYPE) {
            return specifiedTargetEntity;
        } else {
            if (ao instanceof Field) {
                Field f = (Field) ao;
                if (Collection.class.isAssignableFrom(f.getType())) {
                    // this has to work, because otherwise the target entity must be valid
                    ParameterizedType type = (ParameterizedType) f.getGenericType();
                    return (Class<?>) type.getActualTypeArguments()[0];
                }
                return f.getType();
            } else if (ao instanceof Method) {
                Method m = (Method) ao;
                if (Collection.class.isAssignableFrom(m.getReturnType())) {
                    // this has to work, because otherwise the target entity must be valid
                    ParameterizedType type = (ParameterizedType) m.getGenericReturnType();
                    return (Class<?>) type.getActualTypeArguments()[0];
                }
                return m.getReturnType();
            }
        }
    } catch (Exception e) {
        throw new IllegalStateException(errorMessage, e);
    }
    throw new IllegalStateException(errorMessage);
}

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

/**
 * Returns the actual generic type of a class's type parameter of the <code>member</code>.
 * <p>/*  w ww. j a  va2 s .  c  om*/
 * if the <code>member</code> is a field then field's generic types are checked. Otherwise the <code>member</code> is treated a a method
 * and its return type's is checked.
 * <p>
 * 
 * @param member
 *            the member
 * @param index
 *            the index number of the generic parameter
 * @return the class of generic type
 * 
 * @param <X>
 *            the type of the class
 * 
 * @since 2.0.1
 */
@SuppressWarnings("unchecked")
public static <X> Class<X> getGenericType(Member member, int index) {
    Type type;

    if (member instanceof Field) {
        final Field field = (Field) member;
        type = field.getGenericType();

    } else {
        final Method method = (Method) member;
        type = method.getGenericReturnType();
    }

    // if not a parameterized type return null
    if (!(type instanceof ParameterizedType)) {
        return null;
    }

    final ParameterizedType parameterizedType = (ParameterizedType) type;

    final Type[] types = parameterizedType.getActualTypeArguments();

    return (Class<X>) ((types != null) && (index < types.length) ? types[index] : null);
}

From source file:io.coala.factory.ClassUtil.java

/**
 * Get the actual type arguments a child class has used to extend a generic
 * base class. See <a/*from ww w  .  jav a 2  s  . com*/
 * href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860"
 * >description</a>
 * 
 * @param genericAncestorType the base class
 * @param concreteDescendantType the child class
 * @return a list of the raw classes for the actual type arguments.
 */
public static <T> List<Class<?>> getTypeArguments(final Class<T> genericAncestorType,
        final Class<? extends T> concreteDescendantType) {
    // sanity check
    if (genericAncestorType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("genericAncestorType");
    if (concreteDescendantType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("concreteDescendantType");

    Map<Type, Type> resolvedTypes = new HashMap<Type, Type>();
    Type type = concreteDescendantType;
    Class<?> typeClass = getClass(type);

    // start walking up the inheritance hierarchy until we hit parentClass
    while (!genericAncestorType.equals(typeClass)) {
        if (type instanceof Class) {
            // there is no useful information for us in raw types, so just
            // keep going.

            if (genericAncestorType.isInterface()) {
                Type intfType = null;
                for (Type intf : typeClass.getGenericInterfaces()) {
                    if (intf instanceof ParameterizedType
                            && genericAncestorType.equals(((ParameterizedType) intf).getRawType())) {
                        intfType = intf;
                        break;
                    }
                }
                if (intfType == null)
                    type = typeClass.getGenericSuperclass();
                else
                    type = intfType;
            } else
                type = typeClass.getGenericSuperclass();

            if (type == null) {
                if (!typeClass.isInterface()) {
                    LOG.warn("No generic super classes found for child class: " + typeClass + " of parent: "
                            + genericAncestorType);
                    return Collections.emptyList();
                }
                for (Type intf : typeClass.getGenericInterfaces()) {
                    if (intf instanceof ParameterizedType) {
                        type = intf;
                        // TODO try other interfaces if this one fails?
                        break;
                    }
                }
                if (type == null) {
                    LOG.warn("No generic ancestors found for child interface: " + typeClass + " of parent: "
                            + genericAncestorType);
                    return Collections.emptyList();
                }
            }
            // LOG.trace(String.format("Trying generic super of %s: %s",
            // typeClass.getSimpleName(), type));
        } else {
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            final Class<?> rawType = (Class<?>) parameterizedType.getRawType();

            final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
            final TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
            for (int i = 0; i < actualTypeArguments.length; i++) {
                resolvedTypes.put(typeParameters[i], actualTypeArguments[i]);
            }

            if (!genericAncestorType.equals(rawType)) {
                type = rawType.getGenericSuperclass();
                // LOG.trace(String.format(
                // "Trying generic super of child %s: %s", rawType,
                // type));
            }
            // else // done climbing the hierarchy
            // LOG.trace("Matched generic " + type + " to ancestor: "
            // + genericAncestorType);
        }
        typeClass = getClass(type);
        // LOG.trace("Trying generic " + typeClass + " from: "
        // + Arrays.asList(typeClass.getGenericInterfaces()));
    }

    // finally, for each actual type argument provided to baseClass,
    // determine (if possible)
    // the raw class for that type argument.
    final Type[] actualTypeArguments;
    if (type instanceof Class) {
        actualTypeArguments = typeClass.getTypeParameters();
    } else {
        actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
    }

    // resolve types by chasing down type variables.
    final List<Class<?>> parentTypeArguments = new ArrayList<Class<?>>();
    for (Type baseType : actualTypeArguments) {
        while (resolvedTypes.containsKey(baseType))
            baseType = resolvedTypes.get(baseType);

        parentTypeArguments.add(getClass(baseType));
    }
    // LOG.trace(String.format(
    // "Got child %s's type arguments for %s: %s",
    // childClass.getName(), parentClass.getSimpleName(),
    // parentTypeArguments));
    return parentTypeArguments;
}