Java Code Examples for javax.lang.model.util.Elements#getTypeElement()

The following examples show how to use javax.lang.model.util.Elements#getTypeElement() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MountSpecModelFactoryTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  Elements elements = mCompilationRule.getElements();
  Types types = mCompilationRule.getTypes();
  TypeElement typeElement =
      elements.getTypeElement(MountSpecModelFactoryTest.TestMountSpec.class.getCanonicalName());

  mMountSpecModel =
      mFactory.create(
          elements,
          types,
          typeElement,
          mock(Messager.class),
          RunMode.normal(),
          mDependencyInjectionHelper,
          null);
}
 
Example 2
Source File: ElementOverlay.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Element resolve(ASTService ast, Elements elements, String what, Element original, ModuleElement modle) {
    Element result = original;
    
    if (classes.containsKey(what)) {
        result = createElement(ast, elements, what, null, modle);
    }

    if (result == null) {
        result = modle != null ? elements.getTypeElement(modle, what) : elements.getTypeElement(what);
    }

    if (result == null) {
        result = modle != null ? elements.getPackageElement(modle, what) : elements.getPackageElement(what);
    }

    result = createElement(ast, elements, what, result, modle);

    return result;
}
 
Example 3
Source File: ProcessorUtils.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Return the AnnotationMirror for the annotation of the given type on the element provided. */
static AnnotationMirror getAnnotation(
    Elements elementUtils,
    Types typeUtils,
    Element element,
    Class<? extends Annotation> annotation)
    throws OptionProcessorException {
  TypeElement annotationElement = elementUtils.getTypeElement(annotation.getCanonicalName());
  if (annotationElement == null) {
    // This can happen if the annotation is on the -processorpath but not on the -classpath.
    throw new OptionProcessorException(
        element, "Unable to find the type of annotation %s.", annotation);
  }
  TypeMirror annotationMirror = annotationElement.asType();

  for (AnnotationMirror annot : element.getAnnotationMirrors()) {
    if (typeUtils.isSameType(annot.getAnnotationType(), annotationMirror)) {
      return annot;
    }
  }
  // No annotation of this requested type found.
  throw new OptionProcessorException(
      element, "No annotation %s found for this element.", annotation);
}
 
Example 4
Source File: ClipboardHandler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Element fqn2element(final Elements elements, final String fqn) {
    if (fqn == null) {
        return null;
    }
    TypeElement type = elements.getTypeElement(fqn);
    if (type != null) {
        return type;
    }
    int idx = fqn.lastIndexOf('.');
    if (idx > 0) {
        type = elements.getTypeElement(fqn.substring(0, idx));
        String name = fqn.substring(idx + 1);
        if (type != null && name.length() > 0) {
            for (Element el : type.getEnclosedElements()) {
                if (el.getModifiers().contains(Modifier.STATIC) && name.contentEquals(el.getSimpleName())) {
                    return el;
                }
            }
        }
    }
    return null;
}
 
Example 5
Source File: EventMethodExtractorTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodExtraction() {
  Elements elements = mCompilationRule.getElements();
  TypeElement typeElement = elements.getTypeElement(TestClass.class.getCanonicalName());

  List<Class<? extends Annotation>> permittedParamAnnotations = new ArrayList<>();

  ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>> methods =
      EventMethodExtractor.getOnEventMethods(
          elements,
          typeElement,
          permittedParamAnnotations,
          mock(Messager.class),
          RunMode.normal());

  EventMethodExtractorTestHelper.assertMethodExtraction(methods);
}
 
Example 6
Source File: ComponentBodyGeneratorTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testCalculateLevelOfComponentInCollections() {
  Elements elements = mCompilationRule.getElements();
  TypeElement typeElement = elements.getTypeElement(CollectionObject.class.getCanonicalName());
  List<? extends Element> fields = typeElement.getEnclosedElements();
  TypeSpec arg0 = SpecModelUtils.generateTypeSpec(fields.get(0).asType());
  TypeSpec arg1 = SpecModelUtils.generateTypeSpec(fields.get(1).asType());
  TypeSpec arg2 = SpecModelUtils.generateTypeSpec(fields.get(2).asType());

  assertThat(arg0.getClass()).isEqualTo(DeclaredTypeSpec.class);
  assertThat(arg1.getClass()).isEqualTo(DeclaredTypeSpec.class);
  assertThat(arg2.getClass()).isEqualTo(DeclaredTypeSpec.class);
  assertThat(
          ComponentBodyGenerator.calculateLevelOfComponentInCollections((DeclaredTypeSpec) arg0))
      .isEqualTo(1);
  assertThat(
          ComponentBodyGenerator.calculateLevelOfComponentInCollections((DeclaredTypeSpec) arg1))
      .isEqualTo(2);
  assertThat(
          ComponentBodyGenerator.calculateLevelOfComponentInCollections((DeclaredTypeSpec) arg2))
      .isEqualTo(0);
}
 
Example 7
Source File: OperationAnnotationValidator.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv)
{

    Elements elementUtils = processingEnv.getElementUtils();
    TypeElement annotationElement = elementUtils.getTypeElement(MANAGED_OPERATION_CLASS_NAME);

    for (Element e : roundEnv.getElementsAnnotatedWith(annotationElement))
    {
        checkAnnotationIsOnMethodInInterface(annotationElement, e);

        ExecutableElement methodElement = (ExecutableElement) e;

        checkInterfaceExtendsConfiguredObject(annotationElement, methodElement);
        checkMethodArgsAreValid(annotationElement, methodElement);
        checkMethodReturnType(annotationElement, methodElement);

    }
    return false;
}
 
Example 8
Source File: CodeGeneration.java    From requery with Apache License 2.0 6 votes vote down vote up
static void addGeneratedAnnotation(ProcessingEnvironment processingEnvironment,
                                   TypeSpec.Builder builder) {
    Elements elements = processingEnvironment.getElementUtils();
    SourceVersion sourceVersion = processingEnvironment.getSourceVersion();
    AnnotationSpec.Builder annotationBuilder = null;
    if (sourceVersion.compareTo(SourceVersion.RELEASE_8) > 0) {
        ClassName name = ClassName.bestGuess("javax.annotation.processing.Generated");
        annotationBuilder = AnnotationSpec.builder(name);
    } else {
        if (elements.getTypeElement(Generated.class.getCanonicalName()) != null) {
            annotationBuilder = AnnotationSpec.builder(Generated.class);
        }
    }

    if (annotationBuilder != null) {
        builder.addAnnotation(annotationBuilder
                .addMember("value", "$S",
                        EntityProcessor.class.getCanonicalName()).build());
    }
}
 
Example 9
Source File: BasicAnnotationProcessorTest.java    From auto with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that a {@link ProcessingStep} passed to {@link
 * BasicAnnotationProcessor#asStep(ProcessingStep)} still gets passed the correct arguments to
 * {@link Step#process(ImmutableSetMultimap)}.
 */
@Test
public void processingStepAsStepProcessElementsMatchClasses() {
  Elements elements = compilation.getElements();
  String anAnnotationName = AnAnnotation.class.getCanonicalName();
  String referencesAClassName = ReferencesAClass.class.getCanonicalName();
  TypeElement anAnnotationElement = elements.getTypeElement(anAnnotationName);
  TypeElement referencesAClassElement = elements.getTypeElement(referencesAClassName);
  MultiAnnotationProcessingStep processingStep = new MultiAnnotationProcessingStep();

  BasicAnnotationProcessor.asStep(processingStep)
      .process(
          ImmutableSetMultimap.of(
              anAnnotationName,
              anAnnotationElement,
              referencesAClassName,
              referencesAClassElement));

  assertThat(processingStep.getElementsByAnnotation())
      .containsExactly(
          AnAnnotation.class,
          anAnnotationElement,
          ReferencesAClass.class,
          referencesAClassElement);
}
 
Example 10
Source File: KeywordsAndMethodsToFilter.java    From sundrio with Apache License 2.0 5 votes vote down vote up
public KeywordsAndMethodsToFilter(Elements elements, String annotationClassName) {
    this.ELEMENT = elements.getTypeElement(annotationClassName);
    CLASSES_VALUE = ELEMENT.getEnclosedElements().get(0);
    KEYWORDS_VALUE = ELEMENT.getEnclosedElements().get(1);
    METHODS_VALUE = ELEMENT.getEnclosedElements().get(2);

}
 
Example 11
Source File: ManagedAnnotationValidator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv)
{
    Elements elementUtils = processingEnv.getElementUtils();
    Types typeUtils = processingEnv.getTypeUtils();

    TypeElement annotationElement = elementUtils.getTypeElement(MANAGED_ANNOTATION_CLASS_NAME);

    String className = "org.apache.qpid.server.model.ManagedInterface";
    TypeMirror configuredObjectType = getErasure(className);

    for (Element e : roundEnv.getElementsAnnotatedWith(annotationElement))
    {
        if (e.getKind() != ElementKind.INTERFACE)
        {
            processingEnv.getMessager()
                    .printMessage(Diagnostic.Kind.ERROR,
                                  "@"
                                  + annotationElement.getSimpleName()
                                  + " can only be applied to an interface",
                                  e
                                 );
        }


        if(!typeUtils.isAssignable(typeUtils.erasure(e.asType()), configuredObjectType))
        {

            processingEnv.getMessager()
                    .printMessage(Diagnostic.Kind.ERROR,
                                  "@"
                                  + annotationElement.getSimpleName()
                                  + " can only be applied to an interface which extends " + className,
                                  e
                                 );
        }
    }

    return false;
}
 
Example 12
Source File: BiMapProperty.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
private static TypeMirror biMap(
    TypeMirror keyType,
    TypeMirror valueType,
    Elements elements,
    Types types) {
  TypeElement mapType = elements.getTypeElement(BiMap.class.getName());
  return types.getDeclaredType(mapType, keyType, valueType);
}
 
Example 13
Source File: TypeMirrors.java    From FreeBuilder with Apache License 2.0 5 votes vote down vote up
private static TypeMirror rawType(
    Types typeUtils,
    Elements elementUtils,
    String typeSnippet) {
  TypeElement typeElement = elementUtils.getTypeElement(typeSnippet);
  if (typeElement == null && !typeSnippet.contains(".")) {
    typeElement = elementUtils.getTypeElement("java.lang." + typeSnippet);
  }
  Preconditions.checkArgument(typeElement != null, "Unrecognised type '%s'", typeSnippet);
  return typeUtils.erasure(typeElement.asType());
}
 
Example 14
Source File: CompilationRuleTest.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
/**
 * Do some non-trivial operation with {@link Element} instances because they stop working after
 * compilation stops.
 */
@Test public void elementsAreValidAndWorking() {
  Elements elements = compilationRule.getElements();
  TypeElement stringElement = elements.getTypeElement(String.class.getName());
  assertThat(stringElement.getEnclosingElement())
      .isEqualTo(elements.getPackageElement("java.lang"));
}
 
Example 15
Source File: Utils.java    From paperparcel with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the {@link TypeMirror} argument found in a given {@code Parcelable.Creator} type.
 */
static TypeMirror getCreatorArg(Elements elements, Types types, DeclaredType creatorType) {
  TypeElement creatorElement = elements.getTypeElement(PARCELABLE_CREATOR_CLASS_NAME);
  TypeParameterElement param = creatorElement.getTypeParameters().get(0);
  return paramAsMemberOf(types, creatorType, param);
}
 
Example 16
Source File: ErrorEventHandlerGeneratorTest.java    From litho with Apache License 2.0 4 votes vote down vote up
@Test
public void testManualErrorHandlerGeneration() {
  final Elements elements = mCompilationRule.getElements();
  final TypeElement typeElement =
      elements.getTypeElement(ManualErrorHandlerSpec.class.getCanonicalName());
  final Types types = mCompilationRule.getTypes();
  final LayoutSpecModel specModel =
      mLayoutSpecModelFactory.create(
          elements, types, typeElement, mMessager, RunMode.normal(), null, null);

  assertThat(ErrorEventHandlerGenerator.hasOnErrorDelegateMethod(specModel.getDelegateMethods()))
      .isFalse();

  // This verifies that the synthetic model matches the one defined here, i.e. that we
  // internally generate the method we expect.
  final SpecMethodModel<EventMethod, EventDeclarationModel> generatedErrorEventMethod =
      ErrorEventHandlerGenerator.generateErrorEventHandlerDefinition();
  final SpecMethodModel<EventMethod, EventDeclarationModel> localErrorEventMethod =
      specModel.getEventMethods().get(0);

  // These are properties that we can reliably generate as opposed to those which may
  // differ in their runtime representation.
  assertThat(generatedErrorEventMethod)
      .isEqualToComparingOnlyGivenFields(
          localErrorEventMethod,
          "annotations",
          "modifiers",
          "returnTypeSpec",
          "returnType",
          "typeVariables");

  assertThat(generatedErrorEventMethod.name).hasToString(localErrorEventMethod.name.toString());
  assertThat(generatedErrorEventMethod.typeModel.name)
      .hasToString(localErrorEventMethod.typeModel.name.toString());

  assertThat(generatedErrorEventMethod.typeModel.fields).hasSize(1);
  // The Represented object refers to a javax model which we can't obtain here.
  assertThat(generatedErrorEventMethod.typeModel.fields.get(0))
      .isEqualToIgnoringGivenFields(
          localErrorEventMethod.typeModel.fields.get(0), "representedObject");
}
 
Example 17
Source File: ToClasses.java    From sundrio with Apache License 2.0 4 votes vote down vote up
public ToClasses(Elements elements) {
    OPTION = elements.getTypeElement(Option.class.getCanonicalName());
}
 
Example 18
Source File: SensorAnnotationsFileBuilder.java    From SensorAnnotations with Apache License 2.0 4 votes vote down vote up
/**
 * Generates the code for our "Sensor Binder" class and writes it to the same package as the
 * annotated class.
 *
 * @param groupedMethodsMap Map of annotated methods per class.
 * @param elementUtils ElementUtils class from {@link ProcessingEnvironment}.
 * @param filer File writer class from {@link ProcessingEnvironment}.
 * @throws IOException
 * @throws ProcessingException
 */
static void generateCode(@NonNull Map<String, AnnotatedMethodsPerClass> groupedMethodsMap,
    @NonNull Elements elementUtils, @NonNull Filer filer)
    throws IOException, ProcessingException {
    for (AnnotatedMethodsPerClass groupedMethods : groupedMethodsMap.values()) {
        // If we've annotated methods in an activity called "ExampleActivity" then that will be
        // the enclosing type element.
        TypeElement enclosingClassTypeElement =
            elementUtils.getTypeElement(groupedMethods.getEnclosingClassName());

        // Create the parameterized type that our generated class will implement,
        // (such as "SensorBinder<ExampleActivity>").
        ParameterizedTypeName parameterizedInterface = ParameterizedTypeName.get(SENSOR_BINDER,
            TypeName.get(enclosingClassTypeElement.asType()));

        // Create the target parameter that will be used in the constructor and bind method,
        // (such as "ExampleActivity").
        ParameterSpec targetParameter =
            ParameterSpec.builder(TypeName.get(enclosingClassTypeElement.asType()), "target")
                .addModifiers(Modifier.FINAL)
                .build();

        MethodSpec constructor =
            createConstructor(targetParameter, groupedMethods.getItemsMap());
        MethodSpec bindMethod = createBindMethod(targetParameter, groupedMethods);

        TypeSpec sensorBinderClass =
            TypeSpec.classBuilder(enclosingClassTypeElement.getSimpleName() + SUFFIX)
                .addModifiers(Modifier.FINAL)
                .addSuperinterface(parameterizedInterface)
                .addField(SENSOR_MANAGER_FIELD)
                .addField(LISTENER_WRAPPERS_FIELD)
                .addMethod(constructor)
                .addMethod(bindMethod)
                .addMethod(UNBIND_METHOD)
                .build();

        // Output our generated file with the same package as the target class.
        PackageElement packageElement = elementUtils.getPackageOf(enclosingClassTypeElement);
        JavaFileObject jfo =
            filer.createSourceFile(enclosingClassTypeElement.getQualifiedName() + SUFFIX);
        Writer writer = jfo.openWriter();
        JavaFile.builder(packageElement.toString(), sensorBinderClass)
            .addFileComment("This class is generated code from Sensor Lib. Do not modify!")
            .addStaticImport(CONTEXT, "SENSOR_SERVICE")
            .build()
            .writeTo(writer);
        writer.close();
    }
}
 
Example 19
Source File: JavaHintsAnnotationProcessor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private boolean verifyOptionField(VariableElement field) {
    StringBuilder error = new StringBuilder();
    Elements elements = processingEnv.getElementUtils();
    TypeElement jlString = elements.getTypeElement("java.lang.String");

    if (jlString == null) {
        return true;
    }

    Types types = processingEnv.getTypeUtils();
    TypeMirror jlStringType = jlString.asType(); //no type params, no need to erasure

    if (!types.isSameType(field.asType(), jlStringType)) {
        error.append(ERR_RETURN_TYPE);
        error.append("\n");
    }

    if (!field.getModifiers().contains(Modifier.STATIC) || !field.getModifiers().contains(Modifier.FINAL)) {
        error.append(ERR_OPTION_MUST_BE_STATIC_FINAL);
        error.append("\n");
    }

    Object key = field.getConstantValue();

    if (key == null) {
        error.append("Option field not a compile-time constant");
        error.append("\n");
    }

    if (error.length() == 0) {
        return true;
    }

    if (error.charAt(error.length() - 1) == '\n') {
        error.delete(error.length() - 1, error.length());
    }

    processingEnv.getMessager().printMessage(Kind.ERROR, error.toString(), field);

    return false;
}
 
Example 20
Source File: Analyzer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
    public Void visitThrows(ThrowsTree tree, List<ErrorDescription> errors) {
        boolean oldInheritDoc = foundInheritDoc;
        ReferenceTree exName = tree.getExceptionName();
        DocTreePath refPath = new DocTreePath(getCurrentPath(), tree.getExceptionName());
        Element ex = javac.getDocTrees().getElement(refPath);
        Types types = javac.getTypes();
        Elements elements = javac.getElements();
        final TypeElement throwableEl = elements.getTypeElement("java.lang.Throwable");
        final TypeElement errorEl = elements.getTypeElement("java.lang.Error");
        final TypeElement runtimeEl = elements.getTypeElement("java.lang.RuntimeException");
        if(throwableEl == null || errorEl == null || runtimeEl == null) {
            LOG.warning("Broken java-platform, cannot resolve " + throwableEl == null? "java.lang.Throwable" : errorEl == null? "java.lang.Error" : "java.lang.RuntimeException"); //NOI18N
            return null;
        }
        TypeMirror throwable = throwableEl.asType();
        TypeMirror error = errorEl.asType();
        TypeMirror runtime = runtimeEl.asType();
        DocTreePath currentDocPath = getCurrentPath();
        DocTreePathHandle dtph = DocTreePathHandle.create(currentDocPath, javac);
        if(dtph == null) {
            return null;
        }
        DocSourcePositions sp = (DocSourcePositions) javac.getTrees().getSourcePositions();
        int start = (int) sp.getStartPosition(javac.getCompilationUnit(), currentDocPath.getDocComment(), tree);
        int end = (int) sp.getEndPosition(javac.getCompilationUnit(), currentDocPath.getDocComment(), tree);
        if (ex == null || (ex.asType().getKind() == TypeKind.DECLARED
                && types.isAssignable(ex.asType(), throwable))) {
            switch (currentElement.getKind()) {
                case CONSTRUCTOR:
                case METHOD:
                    if (ex == null || !(types.isAssignable(ex.asType(), error)
                            || types.isAssignable(ex.asType(), runtime))) {
                        ExecutableElement ee = (ExecutableElement) currentElement;
                        String fqn;
                        if (ex != null) {
                            fqn = ((TypeElement) ex).getQualifiedName().toString();
                        } else {
                            ExpressionTree referenceClass = javac.getTreeUtilities().getReferenceClass(new DocTreePath(currentDocPath, exName));
                            if(referenceClass == null) break;
                            fqn = referenceClass.toString();
                        }
                        checkThrowsDeclared(tree, ex, fqn, ee.getThrownTypes(), dtph, start, end, errors);
                    }
                    break;
                default:
//                        env.messages.error(REFERENCE, tree, "dc.invalid.throws");
            }
        } else {
//                env.messages.error(REFERENCE, tree, "dc.invalid.throws");
        }
        warnIfEmpty(tree, tree.getDescription());
        super.visitThrows(tree, errors);
        foundInheritDoc = oldInheritDoc;
        return null;
    }