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:com.github.helenusdriver.driver.impl.DataTypeImpl.java

/**
 * Unwraps the specific class if it is an {@link Optional}.
 *
 * @author <a href="mailto:paouelle@enlightedinc.com">paouelle</a>
 *
 * @param  clazz the class to unwrap if required
 * @param  type the corresponding type for the class
 * @return the element of the optional class if it is an optional otherwise
 *         the class itself//from w  w  w .  j  av a  2  s. c  om
 */
public static Class<?> unwrapOptionalIfPresent(Class<?> clazz, Type type) {
    if (Optional.class.isAssignableFrom(clazz)) {
        if (type instanceof ParameterizedType) {
            final ParameterizedType ptype = (ParameterizedType) type;
            final Type atype = ptype.getActualTypeArguments()[0]; // optional will always have 1 argument

            return ReflectionUtils.getRawClass(atype);
        }
    }
    return clazz;
}

From source file:org.kurento.test.base.BrowserTest.java

public static Class<?> getParamType(Class<?> testClass) {

    Type genericSuperclass = testClass.getGenericSuperclass();

    if (genericSuperclass != null) {

        if (genericSuperclass instanceof Class) {
            return getParamType((Class<?>) genericSuperclass);
        }//from  w  ww . ja va 2s  .co m

        ParameterizedType paramClass = (ParameterizedType) genericSuperclass;

        return (Class<?>) paramClass.getActualTypeArguments()[0];
    }

    throw new RuntimeException("Unable to obtain the type paramter of KurentoTest");
}

From source file:jef.tools.collection.CollectionUtil.java

/**
 * ?/*ww  w.j  a va2s. c om*/
 * 
 * @param type
 * @return ??null,???
 */
public static Type getComponentType(Type type) {
    if (type instanceof GenericArrayType) {
        return ((GenericArrayType) type).getGenericComponentType();
    } else if (type instanceof Class) {
        Class<?> rawType = (Class<?>) type;
        if (rawType.isArray()) {
            return rawType.getComponentType();
        } else if (Collection.class.isAssignableFrom(rawType)) {
            // ??Object
            return Object.class;
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pType = (ParameterizedType) type;
        Type rawType = pType.getRawType();
        if (isCollection(rawType)) {
            return pType.getActualTypeArguments()[0];
        }
    }
    return null;
}

From source file:com.github.helenusdriver.driver.impl.DataTypeImpl.java

/**
 * Infers the data type for the specified field.
 *
 * @author paouelle//w  w  w.j av a2 s  .  c om
 *
 * @param  field the non-<code>null</code> field to infer the CQL data type for
 * @param  clazz the non-<code>null</code> class for which to infer the CQL
 *         data type for the field
 * @param  types the non-<code>null</code> list where to add the inferred type and
 *         its arguments
 * @param  persisted the persisted annotation to consider for the field
 * @throws IllegalArgumentException if the data type cannot be inferred from
 *         the field
 */
private static void inferDataTypeFrom(Field field, Class<?> clazz, List<CQLDataType> types,
        Persisted persisted) {
    if (Optional.class.isAssignableFrom(clazz)) {
        org.apache.commons.lang3.Validate.isTrue(types.isEmpty(),
                "collection of optionals is not supported in field: %s", field);
        final Type type = field.getGenericType();

        if (type instanceof ParameterizedType) {
            final ParameterizedType ptype = (ParameterizedType) type;
            final Type atype = ptype.getActualTypeArguments()[0]; // optional will always have 1 argument

            if (persisted != null) {
                types.add(persisted.as());
            } else {
                DataTypeImpl.inferBasicDataTypeFrom(field, ReflectionUtils.getRawClass(atype), types,
                        persisted);
            }
            return;
        }
    } else if (List.class.isAssignableFrom(clazz)) {
        org.apache.commons.lang3.Validate.isTrue(types.isEmpty(),
                "collection of collections is not supported in field: %s", field);
        final Type type = field.getGenericType();

        if (type instanceof ParameterizedType) {
            final ParameterizedType ptype = (ParameterizedType) type;
            final Type atype = ptype.getActualTypeArguments()[0]; // lists will always have 1 argument

            types.add(DataType.LIST);
            if (persisted != null) {
                types.add(persisted.as());
            } else {
                DataTypeImpl.inferDataTypeFrom(field, ReflectionUtils.getRawClass(atype), types);
            }
            return;
        }
    } else if (Set.class.isAssignableFrom(clazz)) {
        org.apache.commons.lang3.Validate.isTrue(types.isEmpty(),
                "collection of collections is not supported in field: %s", field);
        final Type type = field.getGenericType();

        if (type instanceof ParameterizedType) {
            final ParameterizedType ptype = (ParameterizedType) type;
            final Type atype = ptype.getActualTypeArguments()[0]; // sets will always have 1 argument

            types.add(DataType.SET);
            if (persisted != null) {
                types.add(persisted.as());
            } else {
                DataTypeImpl.inferDataTypeFrom(field, ReflectionUtils.getRawClass(atype), types);
            }
            return;
        }
    } else if (Map.class.isAssignableFrom(clazz)) {
        org.apache.commons.lang3.Validate.isTrue(types.isEmpty(),
                "collection of collections is not supported in field: %s", field);
        final Type type = field.getGenericType();

        if (type instanceof ParameterizedType) {
            final ParameterizedType ptype = (ParameterizedType) type;
            final Type ktype = ptype.getActualTypeArguments()[0]; // maps will always have 2 arguments
            final Type vtype = ptype.getActualTypeArguments()[1]; // maps will always have 2 arguments

            types.add(DataType.MAP);
            // don't consider the @Persister annotation for the key
            DataTypeImpl.inferDataTypeFrom(field, ReflectionUtils.getRawClass(ktype), types, null);
            if (persisted != null) {
                types.add(persisted.as());
            } else {
                DataTypeImpl.inferDataTypeFrom(field, ReflectionUtils.getRawClass(vtype), types);
            }
            return;
        }
    }
    DataTypeImpl.inferBasicDataTypeFrom(field, clazz, types, persisted);
}

From source file:com.github.hateoas.forms.spring.SpringActionDescriptor.java

private static String invokeHandlerOrFollowRecurse(final SpringActionInputParameter annotatedParameter,
        final String parentParamName, final Set<String> knownFields, final ActionInputParameterVisitor handler,
        final List<ActionInputParameter> bodyInputParameters, final Object propertyValue,
        final ActionParameterType info) {
    String paramName = info.getParamName();
    ActionParameterType parameterType = info;
    String paramPath = parentParamName + paramName;
    if (info.isSingleValue()) {
        /**//w  ww  .j  a  v  a  2s  . c o m
         * TODO This is a temporal patch, to be reviewed...
         */
        if (annotatedParameter == null) {
            ActionInputParameter inputParameter = new AnnotableSpringActionInputParameter(parameterType,
                    propertyValue, paramPath);
            bodyInputParameters.add(inputParameter);
            handler.visit(inputParameter);
            return inputParameter.getName();
        } else if (!knownFields.contains(parentParamName + paramName)) {
            DTOParam dtoAnnotation = info.getDTOParam();
            StringBuilder sb = new StringBuilder(64);
            if (info.isArrayOrCollection() && dtoAnnotation != null) {
                Object wildCardValue = null;
                if (propertyValue != null) {
                    // if the element is wildcard dto type element we need to get the first value
                    if (info.isArray()) {
                        Object[] array = (Object[]) propertyValue;
                        if (!dtoAnnotation.wildcard()) {
                            for (int i = 0; i < array.length; i++) {
                                if (array[i] != null) {
                                    sb.setLength(0);
                                    recurseBeanCreationParams(array[i].getClass(), annotatedParameter, array[i],
                                            sb.append(parentParamName).append(paramName).append('[').append(i)
                                                    .append("].").toString(),
                                            knownFields, handler, bodyInputParameters);
                                }
                            }
                        } else if (array.length > 0) {
                            wildCardValue = array[0];
                        }
                    } else {
                        int i = 0;
                        if (!dtoAnnotation.wildcard()) {
                            for (Object value : (Collection<?>) propertyValue) {
                                if (value != null) {
                                    sb.setLength(0);
                                    recurseBeanCreationParams(value.getClass(), annotatedParameter, value,
                                            sb.append(parentParamName).append(paramName).append('[').append(i++)
                                                    .append("].").toString(),
                                            knownFields, handler, bodyInputParameters);
                                }
                            }
                        } else if (!((Collection<?>) propertyValue).isEmpty()) {
                            wildCardValue = ((Collection<?>) propertyValue).iterator().next();
                        }
                    }
                }
                if (dtoAnnotation.wildcard()) {
                    Class<?> willCardClass = null;
                    if (wildCardValue != null) {
                        willCardClass = wildCardValue.getClass();
                    } else {
                        ParameterizedType type = parameterType.getParameterizedType();
                        if (type != null) {
                            willCardClass = (Class<?>) type.getActualTypeArguments()[0];
                        }
                    }
                    if (willCardClass != null) {
                        recurseBeanCreationParams(willCardClass, annotatedParameter, wildCardValue,
                                sb.append(parentParamName).append(paramName).append(DTOParam.WILDCARD_LIST_MASK)
                                        .append('.').toString(),
                                knownFields, handler, bodyInputParameters);
                    }
                }
                return parentParamName + paramName;
            } else {
                SpringActionInputParameter inputParameter = new AnnotableSpringActionInputParameter(
                        parameterType, propertyValue, paramPath);
                // TODO We need to find a better solution for this
                inputParameter.possibleValues = annotatedParameter.possibleValues;
                bodyInputParameters.add(inputParameter);
                handler.visit(inputParameter);

                return inputParameter.getName();
            }
        }

    } else {
        Object callValueBean;
        if (propertyValue instanceof Resource) {
            callValueBean = ((Resource<?>) propertyValue).getContent();
        } else {
            callValueBean = propertyValue;
        }
        recurseBeanCreationParams(info.getParameterType(), annotatedParameter, callValueBean, paramPath + ".",
                knownFields, handler, bodyInputParameters);
    }

    return null;
}

From source file:com.wavemaker.json.type.reflect.ReflectTypeUtils.java

/**
 * Initializes a TypeDefinition from a given class. The first entry in the return list is the TypeDefinition for the
 * parameter class; any entries after that (if any) are TypeDefinitions for any other types that were required as
 * fields for that root TypeDefinition./*from   w ww. ja va 2  s . c  o m*/
 * 
 * @param klass The Class object to describe.
 * @param typeState The TypeState for the current operation.
 * @param strict True indicates that processing should stop on ambiguous entries; false indicates that null should
 *        be entered.
 * @return A list of TypeDefinitions; the first entry is the root (corresponding with the klass parameter), any
 *         other entries in the list were required to describe the root TypeDefinition's fields. The return may also
 *         be null, if sufficient information was not provided to determine the type.
 */
public static TypeDefinition getTypeDefinition(Type type, TypeState typeState, boolean strict) {

    Class<?> klass;

    // we already know about this type; we're done
    if (typeState.isTypeKnown(ReflectTypeUtils.getTypeName(type))) {
        return typeState.getType(ReflectTypeUtils.getTypeName(type));
    }

    // if the type is Object, return null, we can't figure out anything more
    if (type instanceof Class && Object.class.equals(type)) {
        return null;
    }

    // if we don't have enough information, return null
    if (!strict) {
        if (type instanceof Class && Map.class.isAssignableFrom((Class<?>) type)
                && !Properties.class.isAssignableFrom((Class<?>) type)) {
            if (!JSON.class.isAssignableFrom((Class<?>) type)) {
                logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(type));
            }
            return null;
        } else if (type instanceof Class && List.class.isAssignableFrom((Class<?>) type)) {
            if (!JSON.class.isAssignableFrom((Class<?>) type)) {
                logger.warn(MessageResource.JSON_TYPE_NOGENERICS.getMessage(type));
            }
            return null;
        }
    }

    TypeDefinition ret;

    if (type instanceof Class && Properties.class.isAssignableFrom((Class<?>) type)) {
        MapReflectTypeDefinition mtdret = new MapReflectTypeDefinition();
        mtdret.setTypeName(ReflectTypeUtils.getTypeName(type));
        mtdret.setShortName(ReflectTypeUtils.getShortName(type));
        typeState.addType(mtdret);

        klass = (Class<?>) type;
        mtdret.setKlass(klass);

        TypeDefinition stringType = getTypeDefinition(String.class, typeState, false);
        mtdret.setKeyFieldDefinition(new GenericFieldDefinition(stringType));
        mtdret.setValueFieldDefinition(new GenericFieldDefinition(stringType));

        ret = mtdret;
    } else if (type instanceof Class && JSONUtils.isPrimitive((Class<?>) type)) {
        PrimitiveReflectTypeDefinition ptret;
        if (((Class<?>) type).isEnum()) {
            ptret = new EnumPrimitiveReflectTypeDefinition();
        } else {
            ptret = new PrimitiveReflectTypeDefinition();
        }

        ptret.setTypeName(ReflectTypeUtils.getTypeName(type));
        ptret.setShortName(ReflectTypeUtils.getShortName(type));
        typeState.addType(ptret);

        klass = (Class<?>) type;
        ptret.setKlass(klass);

        ret = ptret;
    } else if (type instanceof Class) {
        klass = (Class<?>) type;

        if (Collection.class.isAssignableFrom(klass)) {
            throw new WMRuntimeException(MessageResource.JSON_TYPE_NOGENERICS, klass);
        } else if (klass.isArray()) {
            throw new WMRuntimeException(MessageResource.JSON_USE_FIELD_FOR_ARRAY, klass);
        } else if (Map.class.isAssignableFrom(klass)) {
            throw new WMRuntimeException(MessageResource.JSON_TYPE_NOGENERICS, klass);
        } else if (ClassUtils.isPrimitiveOrWrapper(klass) || CharSequence.class.isAssignableFrom(klass)) {
            PrimitiveReflectTypeDefinition ptret = new PrimitiveReflectTypeDefinition();
            ptret.setTypeName(ReflectTypeUtils.getTypeName(type));
            ptret.setShortName(ReflectTypeUtils.getShortName(type));
            typeState.addType(ptret);

            ptret.setKlass(klass);

            ret = ptret;
        } else {
            ObjectReflectTypeDefinition otret = new ObjectReflectTypeDefinition();
            otret.setTypeName(ReflectTypeUtils.getTypeName(type));
            otret.setShortName(ReflectTypeUtils.getShortName(type));
            otret.setKlass(klass);
            typeState.addType(otret);

            PropertyUtilsBean pub = ((ReflectTypeState) typeState).getPropertyUtilsBean();
            PropertyDescriptor[] pds = pub.getPropertyDescriptors(klass);
            otret.setFields(new LinkedHashMap<String, FieldDefinition>(pds.length));

            for (PropertyDescriptor pd : pds) {
                if (pd.getName().equals("class")) {
                    continue;
                }

                Type paramType;
                if (pd.getReadMethod() != null) {
                    paramType = pd.getReadMethod().getGenericReturnType();
                } else if (pd.getWriteMethod() != null) {
                    paramType = pd.getWriteMethod().getGenericParameterTypes()[0];
                } else {
                    logger.warn("No getter in type " + pd.getName());
                    continue;
                }

                otret.getFields().put(pd.getName(),
                        getFieldDefinition(paramType, typeState, strict, pd.getName()));
            }

            ret = otret;
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;

        if (pt.getRawType() instanceof Class && Map.class.isAssignableFrom((Class<?>) pt.getRawType())) {
            MapReflectTypeDefinition mtdret = new MapReflectTypeDefinition();
            mtdret.setTypeName(ReflectTypeUtils.getTypeName(type));
            mtdret.setShortName(ReflectTypeUtils.getShortName(type));
            typeState.addType(mtdret);

            Type[] types = pt.getActualTypeArguments();

            mtdret.setKeyFieldDefinition(getFieldDefinition(types[0], typeState, strict, null));
            mtdret.setValueFieldDefinition(getFieldDefinition(types[1], typeState, strict, null));
            mtdret.setKlass((Class<?>) pt.getRawType());

            ret = mtdret;
        } else {
            throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNRAWTYPE, pt.getOwnerType(), pt);
        }
    } else {
        throw new WMRuntimeException(MessageResource.JSON_TYPE_UNKNOWNPARAMTYPE, type,
                type != null ? type.getClass() : null);
    }

    return ret;
}

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

public static String simpleRepresentation(Type aType) {
    if (aType == null) {
        return "null";
    }//from   w w w . j a va  2  s .  c  o  m
    if (aType instanceof CustomType) {
        return ((CustomType) aType).simpleRepresentation();
    }
    if (aType instanceof Class) {
        return ((Class) aType).getSimpleName();
    } else if (aType instanceof ParameterizedType) {
        ParameterizedType t = (ParameterizedType) aType;
        StringBuilder sb = new StringBuilder();
        sb.append(simpleRepresentation(t.getRawType())).append("<");
        boolean isFirst = true;
        for (Type st : t.getActualTypeArguments()) {
            sb.append(isFirst ? "" : ",").append(simpleRepresentation(st));
            isFirst = false;
        }
        sb.append(">");
        return sb.toString();
    }
    return aType.toString();
}

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

public static String fullQualifiedRepresentation(Type aType) {
    if (aType == null) {
        return null;
    }//w w w  .  ja  va  2  s. c o m
    if (aType instanceof CustomType) {
        return ((CustomType) aType).fullQualifiedRepresentation();
    }
    if (aType instanceof Class) {
        return ((Class) aType).getName();
    } else if (aType instanceof ParameterizedType) {
        ParameterizedType t = (ParameterizedType) aType;
        StringBuilder sb = new StringBuilder();
        sb.append(fullQualifiedRepresentation(t.getRawType())).append("<");
        boolean isFirst = true;
        for (Type st : t.getActualTypeArguments()) {
            sb.append(isFirst ? "" : ",").append(fullQualifiedRepresentation(st));
            isFirst = false;
        }
        sb.append(">");
        return sb.toString();
    }
    return aType.toString();
}

From source file:org.openmainframe.ade.impl.PropertyAnnotation.java

/**
 * Find out what are the concrete classes used in an offspring class for the generic placeholders of a base class/interface
 * /*from  ww w  .  j a  v  a2  s . c  o  m*/
 * @param <T> base class type
 * @param offspring class or interface subclassing or extending the base class
 * @param base class with generic arguments
 * @param actualArgs the actual type arguments passed to the offspring class (omit unless useful)
 * @return actual generic type arguments, must match the type parameters of the offspring class. If omitted, the
 * type parameters will be used instead.
 */
@SuppressWarnings("unchecked")
public static <T> Type[] resolveActualTypeArgs(Class<? extends T> offspring, Class<T> base,
        Type... actualArgs) {

    //  If actual types are omitted, the type parameters will be used instead.
    if (actualArgs.length == 0) {
        actualArgs = offspring.getTypeParameters();
    }
    // map generic parameters into the actual types
    final Map<String, Type> genericVariables = new TreeMap<String, Type>();
    for (int i = 0; i < actualArgs.length; i++) {
        final TypeVariable<?> typeVariable = (TypeVariable<?>) offspring.getTypeParameters()[i];
        genericVariables.put(typeVariable.getName(), actualArgs[i]);
    }

    // Find direct ancestors (superclass, interfaces)
    final List<Type> ancestors = new LinkedList<Type>();
    if (offspring.getGenericSuperclass() != null) {
        ancestors.add(offspring.getGenericSuperclass());
    }
    for (Type t : offspring.getGenericInterfaces()) {
        ancestors.add(t);
    }

    // Recurse into ancestors (superclass, interfaces)
    for (Type type : ancestors) {
        if (type instanceof Class<?>) {
            // ancestor is non-parameterized. Recurse only if it matches the base class.
            final Class<?> ancestorClass = (Class<?>) type;
            if (base.isAssignableFrom(ancestorClass)) {
                final Type[] result = resolveActualTypeArgs((Class<? extends T>) ancestorClass, base);
                if (result != null) {
                    return result;
                }
            }
        }
        if (type instanceof ParameterizedType) {
            // ancestor is parameterized. Recurse only if the raw type matches the base class.
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            final Type rawType = parameterizedType.getRawType();
            if (rawType instanceof Class<?>) {
                final Class<?> rawTypeClass = (Class<?>) rawType;
                if (base.isAssignableFrom(rawTypeClass)) {

                    // loop through all type arguments and replace type variables with the actually known types
                    final List<Type> resolvedTypes = new LinkedList<Type>();
                    for (Type t : parameterizedType.getActualTypeArguments()) {
                        if (t instanceof TypeVariable<?>) {
                            final Type resolvedType = genericVariables.get(((TypeVariable<?>) t).getName());
                            resolvedTypes.add(resolvedType != null ? resolvedType : t);
                        } else if (t instanceof ParameterizedType) {
                            final ParameterizedType pType = (ParameterizedType) t;
                            final Type resolvedPType = new ResolvedParameterizedType(pType, genericVariables);
                            resolvedTypes.add(resolvedPType);
                        } else {
                            resolvedTypes.add(t);
                        }
                    }

                    final Type[] result = resolveActualTypeArgs((Class<? extends T>) rawTypeClass, base,
                            resolvedTypes.toArray(new Type[] {}));
                    if (result != null) {
                        return result;
                    }
                }
            }
        }
    }

    // we have a result if we reached the base class.
    return offspring.equals(base) ? actualArgs : null;
}

From source file:plugins.PlayReader.java

private static Class<?> getClassArgument(Type cls) {
    if (cls instanceof ParameterizedType) {
        final ParameterizedType parameterized = (ParameterizedType) cls;
        final Type[] args = parameterized.getActualTypeArguments();
        if (args.length != 1) {
            Logger.error(String.format("Unexpected class definition: %s", cls));
            return null;
        }// w w  w. j av a 2  s. co m
        final Type first = args[0];
        if (first instanceof Class) {
            return (Class<?>) first;
        } else {
            return null;
        }
    } else {
        Logger.error(String.format("Unknown class definition: %s", cls));
        return null;
    }
}