javax.lang.model.element.TypeElement Java Examples
The following examples show how to use
javax.lang.model.element.TypeElement.
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 Project: openjdk-jdk9 Author: AdoptOpenJDK File: Utils.java License: GNU General Public License v2.0 | 6 votes |
/** * Given a TypeElement, return the name of its type (Class, Interface, etc.). * * @param te the TypeElement to check. * @param lowerCaseOnly true if you want the name returned in lower case. * If false, the first letter of the name is capitalized. * @return */ public String getTypeElementName(TypeElement te, boolean lowerCaseOnly) { String typeName = ""; if (isInterface(te)) { typeName = "doclet.Interface"; } else if (isException(te)) { typeName = "doclet.Exception"; } else if (isError(te)) { typeName = "doclet.Error"; } else if (isAnnotationType(te)) { typeName = "doclet.AnnotationType"; } else if (isEnum(te)) { typeName = "doclet.Enum"; } else if (isOrdinaryClass(te)) { typeName = "doclet.Class"; } typeName = lowerCaseOnly ? toLowerCase(typeName) : typeName; return typeNameMap.computeIfAbsent(typeName, configuration :: getText); }
Example #2
Source Project: netbeans Author: apache File: TestGeneratorSetup.java License: Apache License 2.0 | 6 votes |
/** */ private boolean hasTestableMethods(TypeElement classElem) { List<? extends Element> enclosedElems = classElem.getEnclosedElements(); if (enclosedElems.isEmpty()) { return false; } List<ExecutableElement> methods = ElementFilter.methodsIn(enclosedElems); if (methods.isEmpty()) { return false; } for (ExecutableElement method : methods) { if (isMethodTestable(method)) { return true; } } return false; }
Example #3
Source Project: netbeans Author: apache File: AbstractObjectProvider.java License: Apache License 2.0 | 6 votes |
public static List<Element> getAnnotatedMembers( final String annotationName, final AnnotationModelHelper helper ) { final List<Element> result = new LinkedList<Element>(); try { helper.getAnnotationScanner().findAnnotations( annotationName, EnumSet.of(ElementKind.FIELD, ElementKind.METHOD), new AnnotationHandler() { @Override public void handleAnnotation(TypeElement type, Element element, AnnotationMirror annotation) { result.add(element); } }); } catch (InterruptedException e) { FieldInjectionPointLogic.LOGGER.warning("Finding annotation "+ annotationName+" was interrupted"); // NOI18N } return result; }
Example #4
Source Project: reflection-no-reflection Author: stephanenicolas File: Processor.java License: Apache License 2.0 | 6 votes |
private void addFieldToAnnotationDatabase(Element fieldElement, int level) { Class fieldClass; //System.out.printf("Type: %s, injection: %s \n",typeElementName, fieldName); fieldClass = createClass(fieldElement.asType(), level); final Set<Modifier> modifiers = fieldElement.getModifiers(); String fieldName = fieldElement.getSimpleName().toString(); TypeElement declaringClassElement = (TypeElement) fieldElement.getEnclosingElement(); String declaringClassName = declaringClassElement.getQualifiedName().toString(); final List<Annotation> annotations = extractAnnotations(fieldElement, level); int modifiersInt = convertModifiersFromAnnotationProcessing(modifiers); final Class<?> enclosingClass = Class.forNameSafe(declaringClassName, level + 1); if (level == 0) { final Class<? extends Annotation> annotationType = annotations.get(0).rnrAnnotationType(); Set<Class<?>> classes = mapAnnotationTypeToClassContainingAnnotation.get(annotationType); if (classes == null) { classes = new HashSet<>(); } classes.add(enclosingClass); mapAnnotationTypeToClassContainingAnnotation.put(annotationType, classes); } final Field field = new Field(fieldName, fieldClass, enclosingClass, modifiersInt, annotations); enclosingClass.addField(field); annotatedClassSet.add(enclosingClass); }
Example #5
Source Project: dagger2-sample Author: yongjhih File: MethodSignatureFormatterTest.java License: Apache License 2.0 | 6 votes |
@Test public void methodSignatureTest() { Elements elements = compilationRule.getElements(); TypeElement inner = elements.getTypeElement(InnerClass.class.getCanonicalName()); ExecutableElement method = Iterables.getOnlyElement(methodsIn(inner.getEnclosedElements())); String formatted = new MethodSignatureFormatter(compilationRule.getTypes()).format(method); // This is gross, but it turns out that annotation order is not guaranteed when getting // all the AnnotationMirrors from an Element, so I have to test this chopped-up to make it // less brittle. assertThat(formatted).contains("@Singleton"); assertThat(formatted).doesNotContain("@javax.inject.Singleton"); // maybe more importantly assertThat(formatted) .contains("@dagger.internal.codegen.MethodSignatureFormatterTest.OuterClass.Foo" + "(bar=String.class)"); assertThat(formatted).contains(" String "); // return type compressed assertThat(formatted).contains("int, ImmutableList<Boolean>)"); // parameters compressed. }
Example #6
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: TestSimpleAddRemove.java License: GNU General Public License v2.0 | 6 votes |
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { // System.err.println("TestProcessor.process " + roundEnv); JavacTask task = JavacTask.instance(processingEnv); if (++round == 1) { switch (ak) { case ADD_IN_PROCESSOR: task.addTaskListener(listener); break; case ADD_IN_LISTENER: addInListener(task, TaskEvent.Kind.ANALYZE, listener); break; } } else if (roundEnv.processingOver()) { switch (rk) { case REMOVE_IN_PROCESSOR: task.removeTaskListener(listener); break; case REMOVE_IN_LISTENER: removeInListener(task, TaskEvent.Kind.GENERATE, listener); break; } } return true; }
Example #7
Source Project: netbeans Author: apache File: JpaControllerUtil.java License: Apache License 2.0 | 6 votes |
public static boolean isFieldAccess(TypeElement clazz) { boolean fieldAccess = false; boolean accessTypeDetected = false; TypeElement typeElement = clazz; Name qualifiedName = typeElement.getQualifiedName(); whileloop: while (typeElement != null) { if (isAnnotatedWith(typeElement, "javax.persistence.Entity") || isAnnotatedWith(typeElement, "javax.persistence.MappedSuperclass")) { // NOI18N for (Element element : typeElement.getEnclosedElements()) { if (isAnnotatedWith(element, "javax.persistence.Id") || isAnnotatedWith(element, "javax.persistence.EmbeddedId")) { if (ElementKind.FIELD == element.getKind()) { fieldAccess = true; } accessTypeDetected = true; break whileloop; } } } typeElement = getSuperclassTypeElement(typeElement); } if (!accessTypeDetected) { Logger.getLogger(JpaControllerUtil.class.getName()).log(Level.WARNING, "Failed to detect correct access type for class: {0}", qualifiedName); // NOI18N } return fieldAccess; }
Example #8
Source Project: netbeans Author: apache File: GeneratorUtilitiesTest.java License: Apache License 2.0 | 6 votes |
public void validate(CompilationInfo info) { TypeElement test = info.getElements().getTypeElement("test.Test"); boolean foundCloneMethod = false; boolean foundToStringMethod = false; for (ExecutableElement ee : ElementFilter.methodsIn(test.getEnclosedElements())) { if (ee.getSimpleName().contentEquals("clone")) { if (ee.getParameters().isEmpty()) { assertFalse(foundCloneMethod); foundCloneMethod = true; } } else if (ee.getSimpleName().contentEquals("toString")) { if (ee.getParameters().isEmpty()) { assertFalse(foundToStringMethod); foundToStringMethod = true; } } } assertTrue(foundCloneMethod); assertTrue(foundToStringMethod); }
Example #9
Source Project: netbeans Author: apache File: EnableBeansFilter.java License: Apache License 2.0 | 6 votes |
private void checkSpecializes( TypeElement typeElement, LinkedList<Element> beans, Set<Element> resultElementSet, Set<Element> originalElements) { TypeElement current = typeElement; while( current != null ){ TypeMirror superClass = current.getSuperclass(); if (!(superClass instanceof DeclaredType)) { break; } if (!AnnotationObjectProvider.hasSpecializes(current, getHelper())) { break; } TypeElement superElement = (TypeElement) ((DeclaredType) superClass) .asElement(); if (originalElements.contains(superElement)) { resultElementSet.remove(superElement); } beans.remove( superElement ); if ( !getResult().getTypeElements().contains( superElement)){ break; } current = superElement; } }
Example #10
Source Project: netbeans Author: apache File: JavaSourceHelper.java License: Apache License 2.0 | 6 votes |
public static List<? extends AnnotationMirror> getClassAnnotations(JavaSource source) { final List<? extends AnnotationMirror>[] classAnons = new List[1]; try { source.runUserActionTask(new AbstractTask<CompilationController>() { public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); TypeElement classElement = getTopLevelClassElement(controller); if (classElement == null) { return; } classAnons[0] = controller.getElements().getAllAnnotationMirrors(classElement); } }, true); } catch (IOException ex) { Exceptions.printStackTrace(ex); } return classAnons[0]; }
Example #11
Source Project: netbeans Author: apache File: TypeUtilities.java License: Apache License 2.0 | 6 votes |
@Override public StringBuilder visitDeclared(DeclaredType t, Boolean p) { Element e = t.asElement(); if (e instanceof TypeElement) { TypeElement te = (TypeElement)e; DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString()); Iterator<? extends TypeMirror> it = t.getTypeArguments().iterator(); if (it.hasNext()) { DEFAULT_VALUE.append("<"); //NOI18N while(it.hasNext()) { visit(it.next(), p); if (it.hasNext()) DEFAULT_VALUE.append(", "); //NOI18N } DEFAULT_VALUE.append(">"); //NOI18N } return DEFAULT_VALUE; } else { return DEFAULT_VALUE.append(UNKNOWN); //NOI18N } }
Example #12
Source Project: immutables Author: immutables File: Metaservices.java License: Apache License 2.0 | 6 votes |
private Set<String> useProvidedTypesForServices(TypeElement typeElement, ImmutableList<TypeMirror> typesMirrors) { List<String> wrongTypes = Lists.newArrayList(); List<String> types = Lists.newArrayList(); for (TypeMirror typeMirror : typesMirrors) { if (typeMirror.getKind() != TypeKind.DECLARED || !processing().getTypeUtils().isAssignable(typeElement.asType(), typeMirror)) { wrongTypes.add(typeMirror.toString()); } else { types.add(typeMirror.toString()); } } if (!wrongTypes.isEmpty()) { processing().getMessager().printMessage( Diagnostic.Kind.ERROR, "@Metainf.Service(value = {...}) contains types that are not implemented by " + typeElement.getSimpleName() + ": " + wrongTypes, typeElement, AnnotationMirrors.findAnnotation(typeElement.getAnnotationMirrors(), Metainf.Service.class)); } return FluentIterable.from(types).toSet(); }
Example #13
Source Project: netbeans Author: apache File: JaxWsAddOperation.java License: Apache License 2.0 | 6 votes |
@org.netbeans.api.annotations.common.SuppressWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") public static String getMainClassName(final FileObject classFO) throws IOException { JavaSource javaSource = JavaSource.forFileObject(classFO); final String[] result = new String[1]; javaSource.runUserActionTask(new Task<CompilationController>() { @Override public void run(CompilationController controller) throws IOException { controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED); TypeElement classEl = SourceUtils.getPublicTopLevelElement(controller); if (classEl != null) { result[0] = classEl.getQualifiedName().toString(); } } }, true); return result[0]; }
Example #14
Source Project: auto Author: google File: MoreElementsTest.java License: Apache License 2.0 | 6 votes |
@Test public void getAnnotationMirror() { TypeElement element = compilation.getElements().getTypeElement(AnnotatedAnnotation.class.getCanonicalName()); Optional<AnnotationMirror> documented = MoreElements.getAnnotationMirror(element, Documented.class); Optional<AnnotationMirror> innerAnnotation = MoreElements.getAnnotationMirror(element, InnerAnnotation.class); Optional<AnnotationMirror> suppressWarnings = MoreElements.getAnnotationMirror(element, SuppressWarnings.class); expect.that(documented).isPresent(); expect.that(innerAnnotation).isPresent(); expect.that(suppressWarnings).isAbsent(); Element annotationElement = documented.get().getAnnotationType().asElement(); expect.that(MoreElements.isType(annotationElement)).isTrue(); expect.that(MoreElements.asType(annotationElement).getQualifiedName().toString()) .isEqualTo(Documented.class.getCanonicalName()); annotationElement = innerAnnotation.get().getAnnotationType().asElement(); expect.that(MoreElements.isType(annotationElement)).isTrue(); expect.that(MoreElements.asType(annotationElement).getQualifiedName().toString()) .isEqualTo(InnerAnnotation.class.getCanonicalName()); }
Example #15
Source Project: auto Author: google File: AutoValueProcessor.java License: Apache License 2.0 | 6 votes |
private int writeExtensions( TypeElement type, ExtensionContext context, ImmutableList<AutoValueExtension> applicableExtensions) { int writtenSoFar = 0; for (AutoValueExtension extension : applicableExtensions) { String parentFqName = generatedSubclassName(type, writtenSoFar + 1); String parentSimpleName = TypeSimplifier.simpleNameOf(parentFqName); String classFqName = generatedSubclassName(type, writtenSoFar); String classSimpleName = TypeSimplifier.simpleNameOf(classFqName); boolean isFinal = (writtenSoFar == 0); String source = extension.generateClass(context, classSimpleName, parentSimpleName, isFinal); if (source != null) { source = Reformatter.fixup(source); writeSourceFile(classFqName, source, type); writtenSoFar++; } } return writtenSoFar; }
Example #16
Source Project: sqlitemagic Author: SiimKinks File: Environment.java License: Apache License 2.0 | 6 votes |
public ExtendedTypeElement getAnyTypeElement(TypeMirror typeMirror) { boolean isArrayElement = false; boolean isGenericElement = false; Dual<TypeElement, Boolean> typeElement = getTypeElement(typeMirror); if (typeElement == null) { if (typeMirror instanceof ArrayType) { try { ArrayType arrayType = (ArrayType) typeMirror; typeElement = getTypeElement(arrayType.getComponentType()); isArrayElement = true; } catch (Exception e) { } } else { typeElement = Dual.create(getGenericTypeElement(typeMirror), false); isGenericElement = true; } } return new ExtendedTypeElement(typeElement, typeMirror, isArrayElement, isGenericElement); }
Example #17
Source Project: netbeans Author: apache File: Renderers.java License: Apache License 2.0 | 5 votes |
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if ( value instanceof DefaultMutableTreeNode ) { value = ((DefaultMutableTreeNode)value).getUserObject(); } String name; String toolTip; Icon icon; if (value instanceof TypeElement) { TypeElement te = (TypeElement) value; name = getDisplayName(te); toolTip = getToolTipText(te); icon = UiUtils.getElementIcon( te.getKind(), te.getModifiers() ); } else { name = "??"; toolTip = name = (value == null ? "NULL" : value.toString()); icon = null; } JLabel comp = (JLabel)renderer.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus ); comp.setText( name ); comp.setToolTipText(toolTip); if (icon != null) { comp.setIcon(icon); } // if ( index % 2 > 0 ) { // comp.setBackground( list.getBackground().darker() ); // Too dark // comp.setOpaque( true ); // } return comp; }
Example #18
Source Project: openjdk-jdk8u Author: AdoptOpenJDK File: TypeModeler.java License: GNU General Public License v2.0 | 5 votes |
public static VariableElement getValueMember(TypeElement type) { VariableElement member = null; for (VariableElement field : ElementFilter.fieldsIn(type.getEnclosedElements())) { if ("value".equals(field.getSimpleName().toString())) { member = field; break; } } if (member == null && type.getKind().equals(ElementKind.CLASS)) member = getValueMember(type.getSuperclass()); return member; }
Example #19
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: NoStar.java License: GNU General Public License v2.0 | 5 votes |
public boolean run(DocletEnvironment root) { Set<TypeElement> classes = ElementFilter.typesIn(root.getIncludedElements()); if (classes.size() != 1) throw new Error("1 " + Arrays.asList(classes)); TypeElement self = classes.iterator().next(); DocTrees trees = root.getDocTrees(); DocCommentTree docCommentTree = trees.getDocCommentTree(self); String c = docCommentTree.getFullBody().toString(); System.out.println("\"" + c + "\""); return c.equals("First sentence.\n0\n 1\n 2\n 3\n 4\n 5"); }
Example #20
Source Project: netbeans Author: apache File: ModelUtils.java License: Apache License 2.0 | 5 votes |
public static VariableElement getField(TypeElement clazz, String fieldName) { for (VariableElement field : ElementFilter.fieldsIn(clazz.getEnclosedElements())) { if (field.getSimpleName().contentEquals(fieldName)) { return field; } } return null; }
Example #21
Source Project: auto Author: google File: OverridesTest.java License: Apache License 2.0 | 5 votes |
@Test public void methodParams_NumberList() { TypeElement xCollection = getTypeElement(XCollection.class); TypeElement xNumberList = getTypeElement(XNumberList.class); TypeElement number = getTypeElement(Number.class); ExecutableElement add = getMethod(xCollection, "add", TypeKind.TYPEVAR); List<TypeMirror> params = explicitOverrides.erasedParameterTypes(add, xNumberList); List<TypeMirror> expectedParams = ImmutableList.of(number.asType()); assertTypeListsEqual(params, expectedParams); }
Example #22
Source Project: buck Author: facebook File: TreeBackedTypeElementTest.java License: Apache License 2.0 | 5 votes |
@Test public void testGetSuperclassObjectSuperclassIsObject() throws IOException { compile("class Foo extends java.lang.Object { }"); TypeElement fooElement = elements.getTypeElement("Foo"); DeclaredType superclass = (DeclaredType) fooElement.getSuperclass(); TypeElement objectElement = elements.getTypeElement("java.lang.Object"); assertSame(objectElement, superclass.asElement()); }
Example #23
Source Project: SimpleWeibo Author: 8tory File: TypeSimplifierTest.java License: Apache License 2.0 | 5 votes |
@Override public final boolean process( Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (!testsRan) { testsRan = true; typeUtil = processingEnv.getTypeUtils(); runTests(); } return false; }
Example #24
Source Project: pocketknife Author: hansenji File: BuilderProcessor.java License: Apache License 2.0 | 5 votes |
public Map<TypeElement, BuilderGenerator> findAndParseTargets(RoundEnvironment roundEnv) { Map<TypeElement, BuilderGenerator> targetMap = new LinkedHashMap<TypeElement, BuilderGenerator>(); // @BundleBuilder processBundleBuilder(targetMap, roundEnv); // @IntentBuilder processIntentBuilder(targetMap, roundEnv); // @FragmentBuilder processFragmentBuilder(targetMap, roundEnv); return targetMap; }
Example #25
Source Project: auto Author: google File: AutoValueOrOneOfProcessor.java License: Apache License 2.0 | 5 votes |
private ImmutableList<AnnotationMirror> propertyFieldAnnotations( TypeElement type, ExecutableElement method) { if (!hasAnnotationMirror(method, COPY_ANNOTATIONS_NAME)) { return ImmutableList.of(); } ImmutableSet<String> excludedAnnotations = ImmutableSet.<String>builder() .addAll(getExcludedAnnotationClassNames(method)) .add(Override.class.getCanonicalName()) .build(); // We need to exclude type annotations from the ones being output on the method, since // they will be output as part of the field's type. Set<String> returnTypeAnnotations = getReturnTypeAnnotations(method, this::annotationAppliesToFields); Set<String> nonFieldAnnotations = method .getAnnotationMirrors() .stream() .map(a -> a.getAnnotationType().asElement()) .map(MoreElements::asType) .filter(a -> !annotationAppliesToFields(a)) .map(e -> e.getQualifiedName().toString()) .collect(toSet()); Set<String> excluded = ImmutableSet.<String>builder() .addAll(excludedAnnotations) .addAll(returnTypeAnnotations) .addAll(nonFieldAnnotations) .build(); return annotationsToCopy(type, method, excluded); }
Example #26
Source Project: buck Author: facebook File: TreeBackedTreesTest.java License: Apache License 2.0 | 5 votes |
@Test public void testNoTreeOrPathForPrecompiledCode() throws IOException { compile("class Foo { }"); TypeElement stringElement = elements.getTypeElement("java.lang.String"); assertNull(trees.getTree(stringElement)); assertNull(trees.getPath(stringElement)); }
Example #27
Source Project: qpid-broker-j Author: apache File: OperationAnnotationValidator.java License: Apache License 2.0 | 5 votes |
public void checkMethodReturnType(final TypeElement annotationElement, final ExecutableElement methodElement) { final TypeMirror returnType = methodElement.getReturnType(); if (!(returnType.getKind() == TypeKind.VOID || isValidType(returnType, true))) { processingEnv.getMessager() .printMessage(Diagnostic.Kind.ERROR, "@" + annotationElement.getSimpleName() + " cannot be applied to methods with return type " + returnType.toString(), methodElement ); } }
Example #28
Source Project: openjdk-jdk9 Author: AdoptOpenJDK File: ConstructorWriterImpl.java License: GNU General Public License v2.0 | 5 votes |
/** * Construct a new ConstructorWriterImpl. * * @param writer The writer for the class that the constructors belong to. * @param typeElement the class being documented. */ public ConstructorWriterImpl(SubWriterHolderWriter writer, TypeElement typeElement) { super(writer, typeElement); VisibleMemberMap visibleMemberMap = configuration.getVisibleMemberMap( typeElement, VisibleMemberMap.Kind.CONSTRUCTORS); List<Element> constructors = visibleMemberMap.getMembers(typeElement); for (Element constructor : constructors) { if (utils.isProtected(constructor) || utils.isPrivate(constructor)) { setFoundNonPubConstructor(true); } } }
Example #29
Source Project: netbeans Author: apache File: ModelUtils.java License: Apache License 2.0 | 5 votes |
public static Collection<String> extractAnnotationNames(Element elem) { Collection<String> annotationsOnElement = new LinkedList<String>(); for (AnnotationMirror ann : elem.getAnnotationMirrors()) { TypeMirror annType = ann.getAnnotationType(); Element typeElem = ((DeclaredType) annType).asElement(); String typeName = ((TypeElement) typeElem).getQualifiedName().toString(); annotationsOnElement.add(typeName); } return annotationsOnElement; }
Example #30
Source Project: spring-init Author: spring-projects-experimental File: SlimConfigurationProcessor.java License: Apache License 2.0 | 5 votes |
private Set<TypeElement> collectTypes(RoundEnvironment roundEnv, Predicate<TypeElement> typeSelectionCondition) { Set<TypeElement> types = new HashSet<>(); for (TypeElement type : ElementFilter.typesIn(roundEnv.getRootElements())) { collectTypes(type, types, typeSelectionCondition); } return types; }