Example usage for java.lang.reflect ParameterizedType getRawType

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

Introduction

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

Prototype

Type getRawType();

Source Link

Document

Returns the Type object representing the class or interface that declared this type.

Usage

From source file:com.heisenberg.impl.plugin.Descriptors.java

protected Descriptor getDataTypeDescriptor(Type type, Field field /* passed for error message only */) {
    Descriptor descriptor = dataTypeDescriptorsByValueType.get(type);
    if (descriptor != null) {
        return descriptor;
    }//from   ww w  .  j a v  a 2 s  . c  o m
    if (String.class.equals(type)) {
        return getDataTypeDescriptor(TextType.class, null);
    } else if (type instanceof ParameterizedType) {
        ParameterizedType parametrizedType = (ParameterizedType) type;
        Type rawType = parametrizedType.getRawType();
        Type[] typeArgs = parametrizedType.getActualTypeArguments();

        descriptor = createDataTypeDescriptor(rawType, typeArgs, field);
        dataTypeDescriptorsByValueType.put(type, descriptor);
        return descriptor;
    }
    throw new RuntimeException(
            "Don't know how to handle " + type + "'s.  It's used in configuration field: " + field);
}

From source file:org.soybeanMilk.SbmUtils.java

/**
 * /*from  w ww  .ja v  a  2s  .  co  m*/
 * @param type
 * @param variableTypesMap
 * @return
 * @date 2012-5-14
 */
private static Type reifyInner(Type type, Map<TypeVariable<?>, Type> variableTypesMap) {
    Type result = null;

    if (type instanceof Class<?>) {
        result = type;
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;

        Type[] at = pt.getActualTypeArguments();
        Type[] cat = new Type[at.length];

        //pt?pt??
        boolean reified = true;
        for (int i = 0; i < at.length; i++) {
            cat[i] = reifyInner(at[i], variableTypesMap);

            if (cat[i] != at[i])
                reified = false;
        }

        if (reified)
            result = pt;
        else
            result = new CustomParameterizedType(pt.getRawType(), pt.getOwnerType(), cat);
    } else if (type instanceof GenericArrayType) {
        GenericArrayType gap = (GenericArrayType) type;

        Type ct = gap.getGenericComponentType();
        Type cct = reifyInner(ct, variableTypesMap);

        if (cct == ct)
            result = gap;
        else
            result = new CustomGenericArrayType(cct);
    } else if (type instanceof TypeVariable<?>) {
        TypeVariable<?> tv = (TypeVariable<?>) type;

        if (variableTypesMap != null)
            result = variableTypesMap.get(tv);

        if (result == null) {
            Type[] bounds = tv.getBounds();

            if (bounds == null || bounds.length == 0)
                result = Object.class;
            else
                result = bounds[0];
        }

        result = reifyInner(result, variableTypesMap);
    } else if (type instanceof WildcardType) {
        WildcardType wt = (WildcardType) type;

        Type[] upperBounds = wt.getUpperBounds();

        Type upperType = (upperBounds != null && upperBounds.length > 0 ? upperBounds[0] : null);

        if (upperType == null)
            upperType = Object.class;

        result = reifyInner(upperType, variableTypesMap);
    } else
        result = type;

    return result;
}

From source file:org.raml.emitter.RamlEmitter.java

private void generateSequenceOfMaps(StringBuilder dump, int depth, List seq, ParameterizedType itemType) {
    Type rawType = itemType.getRawType();
    if (rawType instanceof Class && Map.class.isAssignableFrom((Class<?>) rawType)) {
        Type valueType = itemType.getActualTypeArguments()[1];
        if (valueType instanceof Class) {
            dump.append("\n");
            for (Object item : seq) {
                dump.append(indent(depth)).append(YAML_SEQ).append("\n");
                dumpMap(dump, depth + 1, valueType, (Map) item);
            }//from   ww  w . j ava  2  s .  co m
        }
    }
}

From source file:richtercloud.reflection.form.builder.fieldhandler.MappingFieldHandler.java

/**
 * Figures out candidates which the longest common prefix in the
 * {@code fieldParameterizedType} chain of (nested) generic types ignoring
 * specifications of {@link AnyType}. Then determines the candidates with
 * the smallest number of {@link AnyType} specifications in the chain. If
 * there're multiple with the same number of {@link AnyType} chooses the
 * first it finds which might lead to random choices.
 *
 * @param fieldParameterizedType the chain of generic types (remember to
 * retrieve this information with {@link Field#getGenericType() } instead of
 * {@link Field#getType() } from fields)
 * @return the choice result as described above or {@code null} if no
 * candidate exists//ww  w  .  j av a  2 s  .  com
 */
protected Type retrieveClassMappingBestMatch(ParameterizedType fieldParameterizedType) {
    //check in a row (walking a tree doesn't make sense because it's
    //agnostic of the position of the type
    SortedMap<Integer, List<ParameterizedType>> candidates = new TreeMap<>(); //TreeMap is a SortedMap
    for (Type mappingType : classMapping.keySet()) {
        if (!(mappingType instanceof ParameterizedType)) {
            continue;
        }
        ParameterizedType mappingParameterizedType = (ParameterizedType) mappingType;
        if (!mappingParameterizedType.getRawType().equals(fieldParameterizedType.getRawType())) {
            continue;
        }
        Type[] parameterizedTypeArguments = mappingParameterizedType.getActualTypeArguments();
        Type[] fieldParameterizedTypeArguments = fieldParameterizedType.getActualTypeArguments();
        for (int i = 0; i < Math.min(parameterizedTypeArguments.length,
                fieldParameterizedTypeArguments.length); i++) {
            if (fieldParameterizedTypeArguments[i].equals(AnyType.class)) {
                throw new IllegalArgumentException(String.format(
                        "type %s must only be used to declare placeholders in class mapping, not in classes (was used in field type %s",
                        AnyType.class, fieldParameterizedType));
            }
            // only compare raw type to raw type in the chain
            Type fieldParameterizedTypeArgument = fieldParameterizedTypeArguments[i];
            if (fieldParameterizedTypeArgument instanceof ParameterizedType) {
                fieldParameterizedTypeArgument = ((ParameterizedType) fieldParameterizedTypeArgument)
                        .getRawType();
            }
            Type parameterizedTypeArgument = parameterizedTypeArguments[i];
            if (parameterizedTypeArgument instanceof ParameterizedType) {
                parameterizedTypeArgument = ((ParameterizedType) parameterizedTypeArgument).getRawType();
            }
            //record AnyType matches as well
            boolean anyTypeMatch = AnyType.class.equals(parameterizedTypeArgument); //work around sucky debugger
            if (!parameterizedTypeArgument.equals(fieldParameterizedTypeArgument) && !anyTypeMatch) {
                break;
            }
            int matchCount = i + 1;
            List<ParameterizedType> candidateList = candidates.get(matchCount);
            if (candidateList == null) {
                candidateList = new LinkedList<>();
                candidates.put(matchCount, candidateList);
            }
            candidateList.add(mappingParameterizedType);
        }
    }
    if (candidates.isEmpty()) {
        return null; //avoid NoSuchElementException
    }
    List<ParameterizedType> higestCandidatesList = candidates.get(candidates.lastKey());
    int lowestAnyCount = Integer.MAX_VALUE;
    ParameterizedType lowestAnyCountCandidate = null;
    for (ParameterizedType highestCandidateCandidate : higestCandidatesList) {
        int highestCandidateCandidateAnyCount = retrieveAnyCountRecursively(highestCandidateCandidate);
        if (highestCandidateCandidateAnyCount < lowestAnyCount) {
            lowestAnyCount = highestCandidateCandidateAnyCount;
            lowestAnyCountCandidate = highestCandidateCandidate;
        }
    }
    return lowestAnyCountCandidate;
}

From source file:org.xwiki.component.descriptor.DefaultComponentDependency.java

@Override
public void setRole(Class<T> role) {
    Class mapping = getMappingType();

    if (mapping == List.class || mapping == Collection.class || mapping == Map.class
            || mapping == Provider.class) {
        Type ownerType;/*  w ww  .  jav  a2 s .com*/
        Class<?> rawType;
        if (getRoleType() instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) getRoleType();
            ownerType = parameterizedType.getOwnerType();
            rawType = (Class<?>) parameterizedType.getRawType();
        } else {
            ownerType = null;
            rawType = mapping;
        }

        setRoleType(new DefaultParameterizedType(ownerType, rawType, role));
    } else {
        super.setRole(role);
    }
}

From source file:com.astamuse.asta4d.data.DefaultDataTypeTransformer.java

private Pair<Class, Class> extractConvertorTypeInfo(DataValueConvertor convertor) {
    Type[] intfs = convertor.getClass().getGenericInterfaces();
    Class rawCls;/* w w w  .ja  v a2s .  c o  m*/
    for (Type intf : intfs) {
        if (intf instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) intf;
            rawCls = (Class) pt.getRawType();
            if (rawCls.getName().equals(DataValueConvertor.class.getName())
                    || rawCls.getName().equals(DataValueConvertorTargetTypeConvertable.class.getName())) {
                Type[] typeArgs = pt.getActualTypeArguments();
                return Pair.of((Class) typeArgs[0], (Class) typeArgs[1]);
            }
        }
    }
    logger.warn("Could not extract type information from DataTypeConvertor:" + convertor.getClass().getName());
    return null;
}

From source file:com.is.rest.client.RestMethodCache.java

@SuppressWarnings("unchecked")
private void parseMethod() {
    Type type = ResponseTypeUtil.parseResponseType(method);
    if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        rawContainer = parameterizedType.getRawType();
        containerTarget = parameterizedType.getActualTypeArguments()[0];
    } else if (!(type instanceof TypeVariable)) {
        targetType = type;/*  w ww  . j  a v a 2 s. com*/
    }
    if (method.isAnnotationPresent(GET.class)) {
        requestType = RequestType.GET;
        path = method.getAnnotation(GET.class).value();
    } else if (method.isAnnotationPresent(POST.class)) {
        requestType = RequestType.POST;
        path = method.getAnnotation(POST.class).value();
    } else if (method.isAnnotationPresent(PUT.class)) {
        requestType = RequestType.PUT;
        path = method.getAnnotation(PUT.class).value();
    } else if (method.isAnnotationPresent(PATCH.class)) {
        requestType = RequestType.PATCH;
        path = method.getAnnotation(PATCH.class).value();
    } else if (method.isAnnotationPresent(DELETE.class)) {
        requestType = RequestType.DELETE;
        path = method.getAnnotation(DELETE.class).value();
    } else if (method.isAnnotationPresent(HEAD.class)) {
        requestType = RequestType.HEAD;
        path = method.getAnnotation(HEAD.class).value();
    } else {
        throw new IllegalStateException(
                "No http annotation (GET, POST, PUT, DELETE, PATCH, HEAD) found on method" + method);
    }
}

From source file:org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.java

private Type determineInferredType(Method method) {
    if (method == null) {
        return null;
    }//from ww w.j a v a 2s  .c  om

    Type genericParameterType = null;
    boolean hasAck = false;

    for (int i = 0; i < method.getParameterTypes().length; i++) {
        MethodParameter methodParameter = new MethodParameter(method, i);
        /*
         * We're looking for a single non-annotated parameter, or one annotated with @Payload.
         * We ignore parameters with type Message because they are not involved with conversion.
         */
        if (eligibleParameter(methodParameter) && (methodParameter.getParameterAnnotations().length == 0
                || methodParameter.hasParameterAnnotation(Payload.class))) {
            if (genericParameterType == null) {
                genericParameterType = methodParameter.getGenericParameterType();
                if (genericParameterType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
                    if (parameterizedType.getRawType().equals(Message.class)) {
                        genericParameterType = ((ParameterizedType) genericParameterType)
                                .getActualTypeArguments()[0];
                    } else if (parameterizedType.getRawType().equals(List.class)
                            && parameterizedType.getActualTypeArguments().length == 1) {
                        Type paramType = parameterizedType.getActualTypeArguments()[0];
                        this.isConsumerRecordList = paramType.equals(ConsumerRecord.class)
                                || (paramType instanceof ParameterizedType && ((ParameterizedType) paramType)
                                        .getRawType().equals(ConsumerRecord.class));
                        this.isMessageList = paramType.equals(Message.class)
                                || (paramType instanceof ParameterizedType
                                        && ((ParameterizedType) paramType).getRawType().equals(Message.class));
                    }
                }
            } else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Ambiguous parameters for target payload for method " + method
                            + "; no inferred type available");
                }
                break;
            }
        } else if (methodParameter.getGenericParameterType().equals(Acknowledgment.class)) {
            hasAck = true;
        }
    }
    Assert.state(
            !this.isConsumerRecordList || method.getParameterTypes().length == 1
                    || (method.getGenericParameterTypes().length == 2 && hasAck),
            "A parameter of type 'List<ConsumerRecord>' must be the only parameter "
                    + "(except for an optional 'Acknowledgment')");
    Assert.state(
            !this.isMessageList || method.getParameterTypes().length == 1
                    || (method.getGenericParameterTypes().length == 2 && hasAck),
            "A parameter of type 'List<Message<?>>' must be the only parameter "
                    + "(except for an optional 'Acknowledgment')");

    return genericParameterType;
}

From source file:dstrelec.nats.listener.adapter.MessagingMessageListenerAdapter.java

/**
 * Subclasses can override this method to use a different mechanism to determine
 * the target type of the payload conversion.
 * @param method the method.//from   w w w .j  a v  a 2 s.c om
 * @return the type.
 */
protected Type determineInferredType(Method method) {
    if (method == null) {
        return null;
    }

    Type genericParameterType = null;

    for (int i = 0; i < method.getParameterTypes().length; i++) {
        MethodParameter methodParameter = new MethodParameter(method, i);
        /*
         * We're looking for a single non-annotated parameter, or one annotated with @Payload.
         * We ignore parameters with type Message because they are not involved with conversion.
         */
        if (eligibleParameter(methodParameter) && (methodParameter.getParameterAnnotations().length == 0
                || methodParameter.hasParameterAnnotation(Payload.class))) {
            if (genericParameterType == null) {
                genericParameterType = methodParameter.getGenericParameterType();
                if (genericParameterType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
                    if (parameterizedType.getRawType().equals(Message.class)) {
                        genericParameterType = ((ParameterizedType) genericParameterType)
                                .getActualTypeArguments()[0];
                    } else if (parameterizedType.getRawType().equals(List.class)
                            && parameterizedType.getActualTypeArguments().length == 1) {
                        Type paramType = parameterizedType.getActualTypeArguments()[0];
                        this.isConsumerRecordList = paramType.equals(io.nats.client.Message.class)
                                || (paramType instanceof ParameterizedType && ((ParameterizedType) paramType)
                                        .getRawType().equals(io.nats.client.Message.class));
                        this.isMessageList = paramType.equals(Message.class)
                                || (paramType instanceof ParameterizedType
                                        && ((ParameterizedType) paramType).getRawType().equals(Message.class));
                    }
                }
            } else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Ambiguous parameters for target payload for method " + method
                            + "; no inferred type available");
                }
                break;
            }
        }
    }
    Assert.state(!this.isConsumerRecordList || method.getParameterTypes().length == 1,
            "A parameter of type 'List<ConsumerRecord>' must be the only parameter");
    Assert.state(!this.isMessageList || method.getParameterTypes().length == 1,
            "A parameter of type 'List<Message<?>>' must be the only parameter");

    return genericParameterType;
}

From source file:com.frank.search.solr.repository.support.SimpleSolrRepository.java

private ParameterizedType resolveReturnedClassFromGernericType(Class<?> clazz) {
    Object genericSuperclass = clazz.getGenericSuperclass();
    if (genericSuperclass instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
        Type rawtype = parameterizedType.getRawType();
        if (SimpleSolrRepository.class.equals(rawtype)) {
            return parameterizedType;
        }//w  w  w. java2 s. co m
    }
    return resolveReturnedClassFromGernericType(clazz.getSuperclass());
}