Example usage for javax.lang.model.element TypeElement asType

List of usage examples for javax.lang.model.element TypeElement asType

Introduction

In this page you can find the example usage for javax.lang.model.element TypeElement asType.

Prototype

@Override
TypeMirror asType();

Source Link

Document

Returns the type defined by this type element, returning the prototypical type for an element representing a generic type.

Usage

From source file:org.lambdamatic.mongodb.apt.template.TemplateType.java

/**
 * Returns the {@link TemplateType} for the given {@link VariableType}, or throws a
 * {@link MetadataGenerationException} if it was not a known or supported type.
 * /*w  w w.ja  v  a2  s  . c om*/
 * @param variableType the variable to analyze
 * @return the corresponding {@link TemplateType}
 * @throws MetadataGenerationException if the given variable type is not supported
 */
private static TemplateType getMetadataFieldType(final TypeMirror variableType,
        final BiFunction<PrimitiveType, ProcessingEnvironment, TemplateType> primitiveTypeToTemplateType,
        final Function<DeclaredType, TemplateType> embeddedDocumentToTemplateType,
        final BiFunction<TypeMirror, ProcessingEnvironment, TemplateType> collectionToTemplateType,
        final BiFunction<DeclaredType, ProcessingEnvironment, TemplateType> mapToTemplateType,
        final Function<DeclaredType, TemplateType> declaredTypeToTemplateType,
        final ProcessingEnvironment processingEnv) throws MetadataGenerationException {
    if (variableType instanceof PrimitiveType) {
        return primitiveTypeToTemplateType.apply((PrimitiveType) variableType, processingEnv);
    } else if (variableType instanceof DeclaredType) {
        final DeclaredType declaredType = (DeclaredType) variableType;
        final TypeElement declaredElement = (TypeElement) declaredType.asElement();
        if (declaredElement.getAnnotation(EmbeddedDocument.class) != null) {
            // embedded documents
            return embeddedDocumentToTemplateType.apply(declaredType);
        } else if (ElementUtils.isAssignable(declaredType, Collection.class)) {
            // collections (list/set)
            return collectionToTemplateType.apply(declaredType.getTypeArguments().get(0), processingEnv);
        } else if (ElementUtils.isAssignable(declaredType, Map.class)) {
            // map
            return mapToTemplateType.apply(declaredType, processingEnv);
        } else {
            return declaredTypeToTemplateType.apply(declaredType);
        }
    } else if (variableType.getKind() == TypeKind.ARRAY) {
        final TypeMirror componentType = ((ArrayType) variableType).getComponentType();
        if (componentType instanceof PrimitiveType) {
            final PrimitiveType primitiveType = (PrimitiveType) componentType;
            final TypeElement boxedClass = processingEnv.getTypeUtils().boxedClass(primitiveType);
            return collectionToTemplateType.apply(boxedClass.asType(), processingEnv);
        }
        return collectionToTemplateType.apply(componentType, processingEnv);
    }
    throw new MetadataGenerationException("Unexpected variable type: " + variableType);
}

From source file:com.vimeo.stag.processor.utils.TypeUtils.java

@NotNull
private static List<? extends TypeMirror> getParameterizedTypes(@NotNull TypeElement element) {
    return ((DeclaredType) element.asType()).getTypeArguments();
}

From source file:com.vimeo.stag.processor.utils.TypeUtils.java

/**
 * Determines whether or not the Element is a parameterized type.
 * If the element is a parameterized type or contains parameterized type
 * arguments, this method will return false.
 *
 * @param element the element to check./*from ww w  . j a  v  a 2  s.c om*/
 * @return true if the element is not generic and
 * contains no generic type arguments, false otherwise.
 */
public static boolean isParameterizedType(@Nullable TypeElement element) {
    return element != null && isParameterizedType(element.asType());
}

From source file:com.vimeo.stag.processor.utils.TypeUtils.java

/**
 * Retrieves a Map of the inherited concrete member variables of an Element. This takes all the
 * member variables that were inherited from the generic parent class and evaluates what their concrete
 * type will be based on the concrete inherited type. For instance, take the following code example:
 * <pre><code>//from w  w w .j av  a  2s .  c  o  m
 * {@literal Factory<T>} {
 *
 *  {@literal @UseStag}
 *   public T data;
 *
 * }
 *
 * VideoFactory extends {@literal Factory<Video>}{
 *
 *   // other variables in here
 *
 * }
 * </code></pre>
 * In this example, VideoFactory has a public member variable T that is of type Video.
 * Since the Factory class has the UseStag annotation, we cannot just generate
 * parsing code for the Factory class, since it is generic and we need concrete types.
 * Instead when we generate the adapter for VideoFactory, we crawl the inheritance
 * hierarchy gathering the member variables. When we get to VideoFactory, we see it
 * has one member variable, T. We then look at the inherited type, Factory{@literal <Video>},
 * and compare it to the original type, Factory{@literal <T>}, and then infer the type
 * of T to be Video.
 *
 * @param concreteInherited the type inherited for the class you are using, in the example,
 *                          this would be Factory{@literal <Video>}
 * @param genericInherited  the raw type inherited for the class you are using, in the example,
 *                          this would be Factory{@literal <T>}
 * @param members           the member variable map of the field (Element) to their concrete
 *                          type (TypeMirror). This should be retrieved by calling getConcreteMembers
 *                          on the inherited class.
 * @return returns a LinkedHashMap of the member variables mapped to their concrete types for the concrete
 * inherited class. (to maintain the ordering)
 */
@NotNull
public static LinkedHashMap<FieldAccessor, TypeMirror> getConcreteMembers(@NotNull TypeMirror concreteInherited,
        @NotNull TypeElement genericInherited, @NotNull Map<FieldAccessor, TypeMirror> members) {

    DebugLog.log(TAG, "Inherited concrete type: " + concreteInherited.toString());
    DebugLog.log(TAG, "Inherited generic type: " + genericInherited.asType().toString());
    List<? extends TypeMirror> concreteTypes = getParameterizedTypes(concreteInherited);
    List<? extends TypeMirror> inheritedTypes = getParameterizedTypes(genericInherited);

    LinkedHashMap<FieldAccessor, TypeMirror> map = new LinkedHashMap<>();

    for (Entry<FieldAccessor, TypeMirror> member : members.entrySet()) {

        DebugLog.log(TAG, "\t\tEvaluating member - " + member.getValue().toString());

        if (isConcreteType(member.getValue())) {

            DebugLog.log(TAG, "\t\t\tConcrete Type: " + member.getValue().toString());
            map.put(member.getKey(), member.getValue());

        } else {

            if (isParameterizedType(member.getValue())) {

                // HashMap<String, T> ...
                TypeMirror resolvedType = resolveTypeVars(member.getValue(), inheritedTypes, concreteTypes);
                map.put(member.getKey(), resolvedType);

                DebugLog.log(TAG, "\t\t\tGeneric Parameterized Type - " + member.getValue().toString()
                        + " resolved to - " + resolvedType.toString());
            } else {

                int index = inheritedTypes.indexOf(member.getKey().asType());
                TypeMirror concreteType = concreteTypes.get(index);
                map.put(member.getKey(), concreteType);

                DebugLog.log(TAG, "\t\t\tGeneric Type - " + member.getValue().toString() + " resolved to - "
                        + concreteType.toString());
            }
        }
    }
    return map;
}

From source file:org.lambdamatic.mongodb.apt.template.MongoCollectionProducerTemplateContext.java

/**
 * Full constructor//www. j  a  va  2 s  . c o m
 * 
 * @param domainType the {@link TypeElement} to work on.
 * @param annotationProcessor the annotation processor used to generate the
 *        {@link LambdamaticMongoCollection} JavaEE CDI producer
 */
public MongoCollectionProducerTemplateContext(final TypeElement domainType,
        final BaseAnnotationProcessor annotationProcessor) {
    super((DeclaredType) domainType.asType(), annotationProcessor);
}

From source file:org.lambdamatic.mongodb.apt.template.MongoCollectionTemplateContext.java

/**
 * Full constructor//from   w w  w . ja v a 2  s  .c  om
 * 
 * @param domainType the {@link TypeElement} to work on.
 * @param annotationProcessor the annotation processor used to generate the
 *        {@link LambdamaticMongoCollection} implementation
 */
public MongoCollectionTemplateContext(final TypeElement domainType,
        final BaseAnnotationProcessor annotationProcessor) {
    super((DeclaredType) domainType.asType(), annotationProcessor);
    this.collectionName = ElementUtils.getAnnotationValue(domainType.getAnnotation(Document.class),
            docAnnotation -> docAnnotation.collection(), "");
}

From source file:blue.lapis.pore.ap.event.EventVerifierProcessor.java

private void verifySuperClass(TypeElement type) {
    if (!processingEnv.getTypeUtils().isSubtype(type.asType(), bukkitEventType)) {
        processingEnv.getMessager().printMessage(ERROR, "Annotated event does not extent Event", type);
    }//  ww w.j  ava  2  s . c  om
}

From source file:com.rgeldmacher.leash.LeashAnnotationProcessor.java

private boolean typeIsFragment(TypeElement type) {
    return types.isAssignable(type.asType(), elements.getTypeElement("android.app.Fragment").asType()) || types
            .isAssignable(type.asType(), elements.getTypeElement("android.support.v4.app.Fragment").asType());
}

From source file:com.rgeldmacher.leash.LeashAnnotationProcessor.java

private boolean useSupportLibrary(TypeElement type) {
    return types.isAssignable(type.asType(),
            elements.getTypeElement("android.support.v4.app.FragmentActivity").asType())
            || types.isAssignable(type.asType(),
                    elements.getTypeElement("android.support.v4.app.Fragment").asType());
}

From source file:org.jdto.tools.AnnotationConfigVerifier.java

private TypeElement extractTargetType(Element element, TypeElement annotationElement, Messager messager) {

    List<? extends AnnotationMirror> am = element.getAnnotationMirrors();

    for (AnnotationMirror annotationMirror : am) {
        if (annotationMirror.getAnnotationType().equals(annotationElement.asType())) {

            //the annotation has only one argument so is easy to extract the value
            Map<? extends ExecutableElement, ? extends AnnotationValue> map = processingEnv.getElementUtils()
                    .getElementValuesWithDefaults(annotationMirror);

            //iterate and return the first value.
            for (ExecutableElement executableElement : map.keySet()) {

                AnnotationValue val = map.get(executableElement);

                String type = val.getValue().toString();

                return super.processingEnv.getElementUtils().getTypeElement(type);
            }//from   w ww. j  a va 2 s.c om

            return null;

        }
    }

    messager.printMessage(Diagnostic.Kind.ERROR, "Could not find target class on element", element);
    return null;
}