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:org.oncoblocks.centromere.web.controller.RequestUtils.java

/**
 * Inspects a {@link Model} class and returns all of the available and acceptable query parameter
 *   definitions, as a map of parameter names and {@link QueryParameterDescriptor} objects.
 * // www  . j av  a2  s  . c om
 * @param model
 * @return
 */
public static Map<String, QueryParameterDescriptor> getAvailableQueryParameters(Class<? extends Model<?>> model,
        boolean recursive) {
    Map<String, QueryParameterDescriptor> paramMap = new HashMap<>();
    for (Field field : model.getDeclaredFields()) {
        String fieldName = field.getName();
        Class<?> type = field.getType();
        if (Collection.class.isAssignableFrom(field.getType())) {
            ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
            type = (Class<?>) parameterizedType.getActualTypeArguments()[0];
        }
        if (field.isAnnotationPresent(Ignored.class)) {
            continue;
        } else {
            paramMap.put(fieldName,
                    new QueryParameterDescriptor(fieldName, fieldName, type, Evaluation.EQUALS));
        }
        if (field.isAnnotationPresent(ForeignKey.class)) {
            if (!recursive)
                continue;
            ForeignKey foreignKey = field.getAnnotation(ForeignKey.class);
            String relField = !"".equals(foreignKey.rel()) ? foreignKey.rel() : fieldName;
            Map<String, QueryParameterDescriptor> foreignModelMap = getAvailableQueryParameters(
                    foreignKey.model(), false);
            for (QueryParameterDescriptor descriptor : foreignModelMap.values()) {
                String newParamName = relField + "." + descriptor.getParamName();
                descriptor.setParamName(newParamName);
                paramMap.put(newParamName, descriptor);
            }
        }
        if (field.isAnnotationPresent(Aliases.class)) {
            Aliases aliases = field.getAnnotation(Aliases.class);
            for (Alias alias : aliases.value()) {
                paramMap.put(alias.value(),
                        new QueryParameterDescriptor(alias.value(),
                                alias.fieldName().equals("") ? fieldName : alias.fieldName(), type,
                                alias.evaluation()));
            }
        } else if (field.isAnnotationPresent(Alias.class)) {
            Alias alias = field.getAnnotation(Alias.class);
            paramMap.put(alias.value(), new QueryParameterDescriptor(alias.value(),
                    alias.fieldName().equals("") ? fieldName : alias.fieldName(), type, alias.evaluation()));
        }
    }
    return paramMap;
}

From source file:com.arpnetworking.jackson.BuilderDeserializer.java

private static void addTo(final Set<Type> visited, final Map<Class<?>, JsonDeserializer<?>> deserializerMap,
        final Type targetType) {
    if (visited.contains(targetType)) {
        return;/*w w  w  . j  av  a  2 s  .com*/
    }
    visited.add(targetType);

    if (targetType instanceof Class<?>) {
        @SuppressWarnings("unchecked")
        final Class<Object> targetClass = (Class<Object>) targetType;
        try {
            // Look-up and register the builder for this class
            final Class<? extends Builder<? extends Object>> builderClass = getBuilderForClass(targetClass);
            deserializerMap.put(targetClass, BuilderDeserializer.of(builderClass));

            LOGGER.info("Registered builder for class; builderClass=" + builderClass + " targetClass="
                    + targetClass);

            // Process all setters on the builder
            for (final Method method : builderClass.getMethods()) {
                if (isSetterMethod(builderClass, method)) {
                    final Type setterArgumentType = method.getGenericParameterTypes()[0];
                    // Recursively register builders for each setter's type
                    addTo(visited, deserializerMap, setterArgumentType);
                }
            }
        } catch (final ClassNotFoundException e) {
            // Log that the class is not build-able
            LOGGER.debug("Ignoring class without builder; targetClass=" + targetClass);
        }

        // Support for JsonSubTypes annotation
        if (targetClass.isAnnotationPresent(JsonSubTypes.class)) {
            final JsonSubTypes.Type[] subTypes = targetClass.getAnnotation(JsonSubTypes.class).value();
            for (final JsonSubTypes.Type subType : subTypes) {
                addTo(visited, deserializerMap, subType.value());
            }
        }

        // Support for JsonTypeInfo annotation
        // TODO(vkoskela): Support JsonTypeInfo classpath scan [MAI-116]
    }

    if (targetType instanceof ParameterizedType) {
        // Recursively register builders for each parameterized type
        final ParameterizedType targetParameterizedType = (ParameterizedType) targetType;
        final Type rawType = targetParameterizedType.getRawType();
        addTo(visited, deserializerMap, rawType);
        for (final Type argumentActualType : targetParameterizedType.getActualTypeArguments()) {
            addTo(visited, deserializerMap, argumentActualType);
        }
    }
}

From source file:com.stratio.deep.commons.utils.CellsUtils.java

/**
 * Sub document list case./*ww w  .j  av  a 2s . co m*/
 *
 * @param <T>        the type parameter
 * @param type       the type
 * @param jsonObject the json object
 * @return the object
 * @throws IllegalAccessException    the illegal access exception
 * @throws InstantiationException    the instantiation exception
 * @throws InvocationTargetException the invocation target exception
 */
private static <T> Object subDocumentListCase(Type type, List<T> jsonObject)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    ParameterizedType listType = (ParameterizedType) type;

    Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0];

    List list = new ArrayList();
    for (T t : jsonObject) {
        list.add(getObjectFromJson(listClass, (JSONObject) t));
    }

    return list;
}

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

public static IGenericType getObjectType(TypeVariable<?> superTypeParameter, Type superTypeParameterClass,
        PropertyDescriptor descriptor) {
    Method readMethod = descriptor.getReadMethod();
    Class<?> rawType = descriptor.getPropertyType();
    if (readMethod == null) {
        return new ClassGenericType(rawType, null, null);
    }/*from   www .j  a va2  s .c  o m*/
    Type type = readMethod.getGenericReturnType();
    if (type instanceof Class<?> || type instanceof TypeVariable<?>) {
        return new ClassGenericType(rawType, null, null);
    }
    if (type instanceof ParameterizedType) {
        GenericTypeContainer genericType = new GenericTypeContainer(rawType);
        ParameterizedType parameterizedType = (ParameterizedType) type;
        //
        if (superTypeParameter != null && parameterizedType.getActualTypeArguments().length == 1
                && superTypeParameter == parameterizedType.getActualTypeArguments()[0]) {
            genericType.getSubTypes().add(resolveType(superTypeParameterClass));
            return genericType;
        }
        for (Type subType : parameterizedType.getActualTypeArguments()) {
            genericType.getSubTypes().add(resolveType(subType));
        }
        return genericType;
    }
    if (type instanceof GenericArrayType) {
        int dimension = 0;
        Type elementType = null;
        GenericArrayType arrayType = (GenericArrayType) type;
        while (true) {
            dimension++;
            elementType = arrayType.getGenericComponentType();
            if (elementType instanceof GenericArrayType) {
                arrayType = (GenericArrayType) elementType;
                continue;
            }
            break;
        }
        GenericTypeContainer genericType = new GenericTypeContainer(rawType, dimension);
        genericType.getSubTypes().add(resolveType(elementType));
        return genericType;
    }
    Assert.fail(MessageFormat.format("Undefine type: {0} {1}", readMethod, rawType));
    return null;
}

From source file:org.apache.axis2.jaxws.utility.ClassUtils.java

/**
 * //  w  w w  .j  a va  2 s  . c  o  m
 */
public static Set<Class> getClasses(Type type, Set<Class> list) {
    if (list == null) {
        list = new HashSet<Class>();
    }
    try {
        if (type instanceof Class) {
            list.add((Class) type);
        }
        if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) type;
            getClasses(pt.getRawType(), list);
            Type types[] = pt.getActualTypeArguments();
            if (types != null) {
                for (int i = 0; i < types.length; i++) {
                    getClasses(types[i], list);
                }
            }
        }
        if (type instanceof GenericArrayType) {
            GenericArrayType gat = (GenericArrayType) type;
            getClasses(gat.getGenericComponentType(), list);
        }
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("Problem occurred in getClasses. Processing continues " + t);
        }
    }
    return list;
}

From source file:cc.sion.core.utils.Reflections.java

/**
 * ??// w ww .j  a va 2  s.  c  o  m
 *
 * @param clazz
 * @param index
 * @param <T>
 * @return
 */
public static <T> Class<T> findParameterizedType(Class<?> clazz, int index) {
    //getSuperclass()
    //getGenericSuperclass()
    //Type Java ???????
    Type type = clazz.getGenericSuperclass();
    //CGLUB subclass target object()
    if (!(type instanceof ParameterizedType)) {
        type = clazz.getSuperclass().getGenericSuperclass();
    }
    if (!(type instanceof ParameterizedType)) {
        return null;
    }
    //ParameterizedType??
    ParameterizedType p = (ParameterizedType) type;
    //getActualTypeArguments???
    Type[] actualTypeArguments = p.getActualTypeArguments();
    if (actualTypeArguments == null || actualTypeArguments.length == 0) {
        return null;
    }
    return (Class<T>) actualTypeArguments[0];
}

From source file:org.openmrs.module.webservices.rest.web.ConversionUtil.java

/**
 * Converts the given object to the given type
 * /*from w  w w  . j a  v a 2 s. co  m*/
 * @param object
 * @param toType a simple class or generic type
 * @return
 * @throws ConversionException
 * @should convert strings to locales
 * @should convert strings to enum values
 * @should convert to an array
 * @should convert to a class
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object convert(Object object, Type toType) throws ConversionException {
    if (object == null)
        return object;

    Class<?> toClass = toType instanceof Class ? ((Class<?>) toType)
            : (Class<?>) (((ParameterizedType) toType).getRawType());

    // if we're trying to convert _to_ a collection, handle it as a special case
    if (Collection.class.isAssignableFrom(toClass) || toClass.isArray()) {
        if (!(object instanceof Collection))
            throw new ConversionException("Can only convert a Collection to a Collection/Array. Not "
                    + object.getClass() + " to " + toType, null);

        if (toClass.isArray()) {
            Class<?> targetElementType = toClass.getComponentType();
            Collection input = (Collection) object;
            Object ret = Array.newInstance(targetElementType, input.size());

            int i = 0;
            for (Object element : (Collection) object) {
                Array.set(ret, i, convert(element, targetElementType));
                ++i;
            }
            return ret;
        }

        Collection ret = null;
        if (SortedSet.class.isAssignableFrom(toClass)) {
            ret = new TreeSet();
        } else if (Set.class.isAssignableFrom(toClass)) {
            ret = new HashSet();
        } else if (List.class.isAssignableFrom(toClass)) {
            ret = new ArrayList();
        } else {
            throw new ConversionException("Don't know how to handle collection class: " + toClass, null);
        }

        if (toType instanceof ParameterizedType) {
            // if we have generic type information for the target collection, we can use it to do conversion
            ParameterizedType toParameterizedType = (ParameterizedType) toType;
            Type targetElementType = toParameterizedType.getActualTypeArguments()[0];
            for (Object element : (Collection) object)
                ret.add(convert(element, targetElementType));
        } else {
            // otherwise we must just add all items in a non-type-safe manner
            ret.addAll((Collection) object);
        }
        return ret;
    }

    // otherwise we're converting _to_ a non-collection type

    if (toClass.isAssignableFrom(object.getClass()))
        return object;

    // Numbers with a decimal are always assumed to be Double, so convert to Float, if necessary
    if (toClass.isAssignableFrom(Float.class) && object instanceof Double) {
        return new Float((Double) object);
    }

    if (object instanceof String) {
        String string = (String) object;
        Converter<?> converter = getConverter(toClass);
        if (converter != null)
            return converter.getByUniqueId(string);

        if (toClass.isAssignableFrom(Date.class)) {
            ParseException pex = null;
            String[] supportedFormats = { "yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS",
                    "yyyy-MM-dd'T'HH:mm:ssZ", "yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd" };
            for (int i = 0; i < supportedFormats.length; i++) {
                try {
                    Date date = new SimpleDateFormat(supportedFormats[i]).parse(string);
                    return date;
                } catch (ParseException ex) {
                    pex = ex;
                }
            }
            throw new ConversionException(
                    "Error converting date - correct format (ISO8601 Long): yyyy-MM-dd'T'HH:mm:ss.SSSZ", pex);
        } else if (toClass.isAssignableFrom(Locale.class)) {
            return LocaleUtility.fromSpecification(object.toString());
        } else if (toClass.isEnum()) {
            return Enum.valueOf((Class<? extends Enum>) toClass, object.toString());
        } else if (toClass.isAssignableFrom(Class.class)) {
            try {
                return Context.loadClass((String) object);
            } catch (ClassNotFoundException e) {
                throw new ConversionException("Could not convert from " + object.getClass() + " to " + toType,
                        e);
            }
        }
        // look for a static valueOf(String) method (e.g. Double, Integer, Boolean)
        try {
            Method method = toClass.getMethod("valueOf", String.class);
            if (Modifier.isStatic(method.getModifiers()) && toClass.isAssignableFrom(method.getReturnType())) {
                return method.invoke(null, string);
            }
        } catch (Exception ex) {
        }
    } else if (object instanceof Map) {
        return convertMap((Map<String, ?>) object, toClass);
    }
    if (toClass.isAssignableFrom(Double.class) && object instanceof Number) {
        return ((Number) object).doubleValue();
    } else if (toClass.isAssignableFrom(Integer.class) && object instanceof Number) {
        return ((Number) object).intValue();
    }
    throw new ConversionException("Don't know how to convert from " + object.getClass() + " to " + toType,
            null);
}

From source file:com.feilong.core.lang.reflect.TypeUtil.java

/**
 * Extract actual type argument class array.
 *
 * @param parameterizedType//from  w ww. j  a  va  2s .co  m
 *            the parameterized type
 * @return the class<?>[]
 * @see java.lang.reflect.ParameterizedType#getActualTypeArguments()
 * @since 1.1.1
 */
private static Class<?>[] extractActualTypeArgumentClassArray(ParameterizedType parameterizedType) {
    Validate.notNull(parameterizedType, "parameterizedType can't be null/empty!");
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("parameterizedType info:{}", JsonUtil.format(parameterizedType));
    }
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    Validate.notNull(actualTypeArguments, "actualTypeArguments can't be null/empty!");

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("actualTypeArguments:[{}]", JsonUtil.format(actualTypeArguments));
    }
    return convert(actualTypeArguments, Class[].class);
}

From source file:com.github.rvesse.airline.Accessor.java

private static Type[] getTypeParameters(Class<?> desiredType, Type type) {
    if (type instanceof Class) {
        Class<?> rawClass = (Class<?>) type;

        // if this is the collection class we're done
        if (desiredType.equals(type)) {
            return null;
        }/*from w w  w  . jav a 2s  . c  o  m*/

        for (Type iface : rawClass.getGenericInterfaces()) {
            Type[] collectionType = getTypeParameters(desiredType, iface);
            if (collectionType != null) {
                return collectionType;
            }
        }

        return getTypeParameters(desiredType, rawClass.getGenericSuperclass());
    }
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;

        Type rawType = parameterizedType.getRawType();
        if (desiredType.equals(rawType)) {
            return parameterizedType.getActualTypeArguments();
        }

        Type[] collectionTypes = getTypeParameters(desiredType, rawType);
        if (collectionTypes != null) {
            for (int i = 0; i < collectionTypes.length; i++) {
                if (collectionTypes[i] instanceof TypeVariable) {
                    TypeVariable<?> typeVariable = (TypeVariable<?>) collectionTypes[i];
                    TypeVariable<?>[] rawTypeParams = ((Class<?>) rawType).getTypeParameters();
                    for (int j = 0; j < rawTypeParams.length; j++) {
                        if (typeVariable.getName().equals(rawTypeParams[j].getName())) {
                            collectionTypes[i] = parameterizedType.getActualTypeArguments()[j];
                        }
                    }
                }
            }
        }
        return collectionTypes;
    }
    return null;
}

From source file:com.taobao.rpc.doclet.RPCAPIInfoHelper.java

/**
 * ?/* w w  w. ja  v  a 2  s .  co m*/
 * 
 * @param method
 * @return
 */
public static Object buildTypeStructure(Class<?> type, Type genericType, Type oriGenericType) {
    if ("void".equalsIgnoreCase(type.getName()) || ClassUtils.isPrimitiveOrWrapper(type)
            || String.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type)
            || URL.class.isAssignableFrom(type)) {
        // 
        return type.getName().replaceAll("java.lang.", "").replaceAll("java.util.", "").replaceAll("java.sql.",
                "");
    } // end if

    if (type.isArray()) {
        // 
        return new Object[] {
                buildTypeStructure(type.getComponentType(), type.getComponentType(), genericType) };
    } // end if

    if (ClassUtils.isAssignable(Map.class, type)) {
        // Map
        return Map.class.getName();
    } // end if

    if (type.isEnum()) {
        // Enum
        return Enum.class.getName();
    } // end if

    boolean isCollection = type != null ? Collection.class.isAssignableFrom(type) : false;

    if (isCollection) {

        Type rawType = type;
        if (genericType != null) {
            if (genericType instanceof ParameterizedType) {
                ParameterizedType _type = (ParameterizedType) genericType;
                Type[] actualTypeArguments = _type.getActualTypeArguments();
                rawType = actualTypeArguments[0];

            } else if (genericType instanceof GenericArrayType) {
                rawType = ((GenericArrayType) genericType).getGenericComponentType();
            }

            if (genericType instanceof WildcardType) {
                rawType = ((WildcardType) genericType).getUpperBounds()[0];
            }
        }

        if (rawType == type) {

            return new Object[] { rawType.getClass().getName() };
        } else {

            if (rawType.getClass().isAssignableFrom(TypeVariableImpl.class)) {
                return new Object[] { buildTypeStructure(
                        (Class<?>) ((ParameterizedType) oriGenericType).getActualTypeArguments()[0], rawType,
                        genericType) };
            } else {
                if (rawType instanceof ParameterizedType) {
                    if (((ParameterizedType) rawType).getRawType() == Map.class) {
                        return new Object[] { Map.class.getName() };
                    }
                }
                if (oriGenericType == rawType) {
                    return new Object[] { rawType.getClass().getName() };
                }
                return new Object[] { buildTypeStructure((Class<?>) rawType, rawType, genericType) };
            }
        }
    }

    if (type.isInterface()) {
        return type.getName();
    }

    ClassInfo paramClassInfo = RPCAPIDocletUtil.getClassInfo(type.getName());
    //added 
    if (null == paramClassInfo) {
        System.out.println("failed to get paramClassInfo for :" + type.getName());
        return null;
    }

    List<FieldInfo> typeConstructure = new ArrayList<FieldInfo>();

    BeanWrapper bean = new BeanWrapperImpl(type);

    PropertyDescriptor[] propertyDescriptors = bean.getPropertyDescriptors();
    Method readMethod;

    String name;

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        readMethod = propertyDescriptor.getReadMethod();

        if (readMethod == null || "getClass".equals(readMethod.getName())) {
            continue;
        }

        name = propertyDescriptor.getName();

        FieldInfo fieldInfo = paramClassInfo.getFieldInfo(name);
        if (readMethod.getReturnType().isAssignableFrom(type)) {
            String comment = "structure is the same with parent.";
            typeConstructure
                    .add(FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", comment));
        } else {
            typeConstructure.add(
                    FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", buildTypeStructure(
                            readMethod.getReturnType(), readMethod.getGenericReturnType(), genericType)));
        } // end if
    }

    return typeConstructure;
}