Search in sources :

Example 31 with Elements

use of javax.lang.model.util.Elements in project auto by google.

the class MoreTypesTest method testReferencedTypes.

@Test
public void testReferencedTypes() {
    Elements elements = compilationRule.getElements();
    TypeElement testDataElement = elements.getTypeElement(ReferencedTypesTestData.class.getCanonicalName());
    ImmutableMap<String, VariableElement> fieldIndex = FluentIterable.from(ElementFilter.fieldsIn(testDataElement.getEnclosedElements())).uniqueIndex(new Function<VariableElement, String>() {

        @Override
        public String apply(VariableElement input) {
            return input.getSimpleName().toString();
        }
    });
    TypeElement objectElement = elements.getTypeElement(Object.class.getCanonicalName());
    TypeElement stringElement = elements.getTypeElement(String.class.getCanonicalName());
    TypeElement integerElement = elements.getTypeElement(Integer.class.getCanonicalName());
    TypeElement setElement = elements.getTypeElement(Set.class.getCanonicalName());
    TypeElement mapElement = elements.getTypeElement(Map.class.getCanonicalName());
    TypeElement charSequenceElement = elements.getTypeElement(CharSequence.class.getCanonicalName());
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f1").asType())).containsExactly(objectElement);
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f2").asType())).containsExactly(setElement, stringElement);
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f3").asType())).containsExactly(mapElement, stringElement, objectElement);
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f4").asType())).containsExactly(integerElement);
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f5").asType())).containsExactly(setElement);
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f6").asType())).containsExactly(setElement, charSequenceElement);
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f7").asType())).containsExactly(mapElement, stringElement, setElement, charSequenceElement);
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f8").asType())).containsExactly(stringElement);
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f9").asType())).containsExactly(stringElement);
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f10").asType())).isEmpty();
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f11").asType())).isEmpty();
    assertThat(MoreTypes.referencedTypes(fieldIndex.get("f12").asType())).containsExactly(setElement, stringElement);
}
Also used : ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) TypeElement(javax.lang.model.element.TypeElement) VariableElement(javax.lang.model.element.VariableElement) Elements(javax.lang.model.util.Elements) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Test(org.junit.Test)

Example 32 with Elements

use of javax.lang.model.util.Elements in project auto by google.

the class MoreElementsTest method getLocalAndInheritedMethods_AbstractList.

// Test that getLocalAndInheritedMethods does the right thing with AbstractList. That class
// inherits from Collection along two paths, via its parent AbstractCollection (which implements
// Collection) and via its parent List (which extends Collection). Bugs in the past have meant
// that the multiple paths might lead the code into thinking that all the abstract methods of
// Collection were still abstract in the AbstractList subclasses here, even though most of them
// are implemented in AbstractList.
@Test
public void getLocalAndInheritedMethods_AbstractList() {
    Elements elements = compilation.getElements();
    TypeElement abstractType = elements.getTypeElement(AbstractAbstractList.class.getCanonicalName());
    Set<ExecutableElement> abstractTypeMethods = MoreElements.getLocalAndInheritedMethods(abstractType, elements);
    assertThat(abstractMethodNamesFrom(abstractTypeMethods)).containsExactly("get", "size");
    TypeElement concreteType = elements.getTypeElement(ConcreteAbstractList.class.getCanonicalName());
    Set<ExecutableElement> concreteTypeMethods = MoreElements.getLocalAndInheritedMethods(concreteType, elements);
    assertThat(abstractMethodNamesFrom(concreteTypeMethods)).isEmpty();
}
Also used : TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Elements(javax.lang.model.util.Elements) Test(org.junit.Test)

Example 33 with Elements

use of javax.lang.model.util.Elements in project auto by google.

the class ExtensionTest method testCantConsumeNonExistentMethod.

@Test
public void testCantConsumeNonExistentMethod() throws Exception {
    class ConsumeBogusMethod extends NonFinalExtension {

        @Override
        public Set<ExecutableElement> consumeMethods(Context context) {
            // Find Integer.intValue() and try to consume that.
            Elements elementUtils = context.processingEnvironment().getElementUtils();
            TypeElement javaLangInteger = elementUtils.getTypeElement(Integer.class.getName());
            for (ExecutableElement method : ElementFilter.methodsIn(javaLangInteger.getEnclosedElements())) {
                if (method.getSimpleName().contentEquals("intValue")) {
                    return ImmutableSet.of(method);
                }
            }
            throw new AssertionError("Could not find Integer.intValue()");
        }
    }
    JavaFileObject impl = JavaFileObjects.forSourceLines("foo.bar.Baz", "package foo.bar;", "import com.google.auto.value.AutoValue;", "@AutoValue public abstract class Baz {", "  abstract String foo();", "}");
    assertThat(impl).processedWith(new AutoValueProcessor(ImmutableList.of(new ConsumeBogusMethod()))).failsToCompile().withErrorContaining("wants to consume a method that is not one of the abstract methods in this class").in(impl).onLine(3).and().withErrorContaining("intValue").in(impl).onLine(3);
}
Also used : JavaFileObject(javax.tools.JavaFileObject) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Elements(javax.lang.model.util.Elements) Test(org.junit.Test)

Example 34 with Elements

use of javax.lang.model.util.Elements in project maven-plugins by apache.

the class SimpleAnnotationProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (annotations.isEmpty()) {
        return true;
    }
    // assert that commons-lang3 is on the classpath
    try {
        getClass().getClassLoader().loadClass("org.apache.commons.lang3.StringUtils");
    } catch (ClassNotFoundException expected) {
        throw new RuntimeException("Expected org.apache.commons.lang3.StringUtils to be on the processorpath," + "because it is a declared dependency of the annotation processor.");
    }
    // assert that commons-io is NOT on the classpath, as it is only a project dependency in "annotation-user"
    try {
        getClass().getClassLoader().loadClass("org.apache.commons.io.IOUtils");
        throw new RuntimeException("Expected a ClassNotFoundException because " + "org.apache.commons.io.IOUtils is not supposed to be on the processorpath.");
    } catch (ClassNotFoundException expected) {
    // expected.
    }
    Filer filer = processingEnv.getFiler();
    Elements elementUtils = processingEnv.getElementUtils();
    Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotations.iterator().next());
    for (Element element : elements) {
        Name name = element.getSimpleName();
        PackageElement packageElement = elementUtils.getPackageOf(element);
        try {
            Name packageName = packageElement.getQualifiedName();
            FileObject resource = filer.createResource(StandardLocation.SOURCE_OUTPUT, packageName, name + ".txt", element);
            Writer writer = resource.openWriter();
            writer.write(name.toString());
            writer.close();
            String className = name + "Companion";
            JavaFileObject javaFile = filer.createSourceFile(packageName + "." + className, element);
            Writer javaWriter = javaFile.openWriter();
            javaWriter.append("package ").append(packageName).append(";\n\n");
            javaWriter.append("public class ").append(className).append(" {\n");
            javaWriter.append("    public ").append(className).append("() {\n");
            javaWriter.append("        System.out.println(\"Hey there!\");\n");
            javaWriter.append("    }\n}\n");
            javaWriter.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return !elements.isEmpty();
}
Also used : PackageElement(javax.lang.model.element.PackageElement) Element(javax.lang.model.element.Element) TypeElement(javax.lang.model.element.TypeElement) IOException(java.io.IOException) Elements(javax.lang.model.util.Elements) Name(javax.lang.model.element.Name) JavaFileObject(javax.tools.JavaFileObject) PackageElement(javax.lang.model.element.PackageElement) FileObject(javax.tools.FileObject) JavaFileObject(javax.tools.JavaFileObject) Filer(javax.annotation.processing.Filer) Writer(java.io.Writer)

Example 35 with Elements

use of javax.lang.model.util.Elements in project ceylon-compiler by ceylon.

the class T6358786 method main.

public static void main(String... args) throws IOException {
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    String srcdir = System.getProperty("test.src");
    File file = new File(srcdir, args[0]);
    JavacTaskImpl task = (JavacTaskImpl) tool.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(Arrays.asList(file)));
    Elements elements = task.getElements();
    for (TypeElement clazz : task.enter(task.parse())) {
        String doc = elements.getDocComment(clazz);
        if (doc == null)
            throw new AssertionError(clazz.getSimpleName() + ": no doc comment");
        System.out.format("%s: %s%n", clazz.getSimpleName(), doc);
    }
}
Also used : JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements)

Aggregations

Elements (javax.lang.model.util.Elements)66 TypeElement (javax.lang.model.element.TypeElement)44 TypeMirror (javax.lang.model.type.TypeMirror)28 VariableElement (javax.lang.model.element.VariableElement)19 ExecutableElement (javax.lang.model.element.ExecutableElement)17 Types (javax.lang.model.util.Types)17 Element (javax.lang.model.element.Element)15 LinkedHashSet (java.util.LinkedHashSet)14 XmlElements (javax.xml.bind.annotation.XmlElements)14 Metadata (org.apache.camel.spi.Metadata)14 Test (org.junit.Test)14 AnnotationProcessorHelper.findTypeElement (org.apache.camel.tools.apt.AnnotationProcessorHelper.findTypeElement)12 Set (java.util.Set)9 TreeSet (java.util.TreeSet)9 Map (java.util.Map)8 ArrayList (java.util.ArrayList)6 LinkedHashMap (java.util.LinkedHashMap)6 List (java.util.List)6 Optional (java.util.Optional)6 ProcessingEnvironment (javax.annotation.processing.ProcessingEnvironment)6