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 File: Utils.java From openjdk-jdk9 with 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 File: Environment.java From sqlitemagic with 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 #3
Source File: AbstractObjectProvider.java From netbeans with 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 File: AutoValueProcessor.java From auto with 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 #5
Source File: TestGeneratorSetup.java From netbeans with 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 #6
Source File: JavaSourceHelper.java From netbeans with 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 #7
Source File: MoreElementsTest.java From auto with 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 #8
Source File: JaxWsAddOperation.java From netbeans with 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 #9
Source File: Metaservices.java From immutables with 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 #10
Source File: Processor.java From reflection-no-reflection with 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 #11
Source File: TypeUtilities.java From netbeans with 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 File: EnableBeansFilter.java From netbeans with 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 #13
Source File: GeneratorUtilitiesTest.java From netbeans with 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 #14
Source File: MethodSignatureFormatterTest.java From dagger2-sample with 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 #15
Source File: JpaControllerUtil.java From netbeans with 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 #16
Source File: TestSimpleAddRemove.java From openjdk-jdk9 with 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 #17
Source File: ClassUseMapper.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private <T extends Element> void add(Map<TypeElement, List<T>> map, TypeElement te, T ref) { // add to specified map refList(map, te).add(ref); // add ref's package to package map and class map packageSet(te).add(elementUtils.getPackageOf(ref)); TypeElement entry = (utils.isField((Element) ref) || utils.isConstructor((Element) ref) || utils.isMethod((Element) ref)) ? (TypeElement) ref.getEnclosingElement() : (TypeElement) ref; classSet(te).add(entry); }
Example #18
Source File: AnnotatedCommandSourceGenerator.java From picocli with Apache License 2.0 | 5 votes |
private String extractClassName(Object object) { if (object instanceof ITypeMetaData) { ITypeMetaData metaData = (ITypeMetaData) object; return importer.getImportedName(metaData.getTypeMirror().toString()); } else if (object instanceof Element) { TypeElement typeElement = (TypeElement) object; return importer.getImportedName(typeElement.getQualifiedName().toString()); } else { return importer.getImportedName(object.getClass().getCanonicalName()); } }
Example #19
Source File: ElementUtilTest.java From j2objc with Apache License 2.0 | 5 votes |
public void testGetAnnotationValue() throws IOException { CompilationUnit unit = translateType("Example", "@com.google.j2objc.annotations.ObjectiveCName(\"E\") class Example {}"); AbstractTypeDeclaration decl = unit.getTypes().get(0); TypeElement element = decl.getTypeElement(); AnnotationMirror annotation = ElementUtil.getAnnotation(element, ObjectiveCName.class); Object value = ElementUtil.getAnnotationValue(annotation, "value"); assertEquals("E", value); }
Example #20
Source File: RegistrationAnnotatedClassCreator.java From Alligator with MIT License | 5 votes |
public RegistrationAnnotatedClass create(Element element) throws ProcessingException { TypeElement classElement = obtainClassElement(element); checkThatIsPublic(classElement); checkThatIsNotAbstract(classElement); ScreenType screenType = obtainScreenType(classElement); String screenClassName = obtainScreenClassName(classElement); String screenResultClassName = obtainScreenResultClassName(classElement); return new RegistrationAnnotatedClass(classElement, screenType, screenClassName, screenResultClassName); }
Example #21
Source File: GenerationUtilsTest.java From netbeans with Apache License 2.0 | 5 votes |
public void testCreateType() throws Exception { TestUtilities.copyStringToFileObject(testFO, "package foo;" + "public class TestClass {" + "}"); runModificationTask(testFO, new Task<WorkingCopy>() { public void run(WorkingCopy copy) throws Exception { GenerationUtils genUtils = GenerationUtils.newInstance(copy); TypeElement scope = SourceUtils.getPublicTopLevelElement(copy); assertNotNull(genUtils.createType("byte[]", scope)); } }); }
Example #22
Source File: OptionAnnotationProcessor.java From netbeans with Apache License 2.0 | 5 votes |
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (delegate() != null) { return delegate().process(annotations, roundEnv); } else { return true; } }
Example #23
Source File: OuterReferenceResolver.java From j2objc with Apache License 2.0 | 5 votes |
@Override public void endVisit(CreationReference node) { Type typeNode = node.getType(); TypeMirror creationType = typeNode.getTypeMirror(); if (TypeUtil.isArray(creationType)) { // Nothing to capture for array creations. return; } TypeElement lambdaType = node.getTypeElement(); pushType(lambdaType); // This is kind of messy, but we use the Type child node as the key for capture scope to be // transferred to the inner ClassInstanceCreation. The capture scope of the CreationReference // node will be transferred to the ClassInstanceCreation that creates the lambda instance. TypeElement creationElement = TypeUtil.asTypeElement(creationType); whenNeedsOuterParam(creationElement, () -> { TypeElement enclosingTypeElement = ElementUtil.getDeclaringClass(creationElement); node.setCreationOuterArg(getOuterPathInherited(enclosingTypeElement)); }); if (ElementUtil.isLocal(creationElement)) { onExitScope(creationElement, () -> { addCaptureArgs(creationElement, node.getCreationCaptureArgs()); }); } popType(); endVisitFunctionalExpression(node); }
Example #24
Source File: InterceptorBindingsTest.java From netbeans with Apache License 2.0 | 5 votes |
private Set<String> getIBindingFqns( Collection<AnnotationMirror> interceptorBindings ) { Set<String> fqns = new HashSet<String>(); for (AnnotationMirror annotationMirror : interceptorBindings) { Element iBinding = annotationMirror.getAnnotationType().asElement(); if ( iBinding instanceof TypeElement ){ fqns.add( ((TypeElement)iBinding).getQualifiedName().toString()); } } return fqns; }
Example #25
Source File: EnterpriseBeansImpl.java From netbeans with Apache License 2.0 | 5 votes |
public List<SessionImpl> createObjects(TypeElement type) { final List<SessionImpl> result = new ArrayList<SessionImpl>(); if (helper.hasAnnotation(type.getAnnotationMirrors(), "javax.ejb.Stateless")) { // NOI18N result.add(new SessionImpl(SessionImpl.Kind.STATELESS, helper, type)); } if (helper.hasAnnotation(type.getAnnotationMirrors(), "javax.ejb.Stateful")) { // NOI18N result.add(new SessionImpl(SessionImpl.Kind.STATEFUL, helper, type)); } if (helper.hasAnnotation(type.getAnnotationMirrors(), "javax.ejb.Singleton")) { // NOI18N result.add(new SessionImpl(SessionImpl.Kind.SINGLETON, helper, type)); } return result; }
Example #26
Source File: BuilderFactoryTest.java From FreeBuilder with Apache License 2.0 | 5 votes |
@Test public void testExplicitNoArgsConstructor() { TypeElement builderType = (TypeElement) model.newElementWithMarker( "package com.example;", "class ExplicitNoArgsConstructor {", " ---> class Builder {", " Builder() {}", " }", "}"); Optional<BuilderFactory> factory = BuilderFactory.from(builderType); assertThat(factory.get()).isEqualTo(NO_ARGS_CONSTRUCTOR); }
Example #27
Source File: CompileWorker.java From netbeans with Apache License 2.0 | 5 votes |
public static ParsingOutput success ( @NullAllowed final String moduleName, final Map<JavaFileObject, List<String>> file2FQNs, final Set<ElementHandle<TypeElement>> addedTypes, final Set<ElementHandle<ModuleElement>> addedModules, final Set<File> createdFiles, final Set<Indexable> finishedFiles, final Set<ElementHandle<TypeElement>> modifiedTypes, final Set<javax.tools.FileObject> aptGenerated) { return new ParsingOutput(true, false, moduleName, file2FQNs, addedTypes, addedModules, createdFiles, finishedFiles, modifiedTypes, aptGenerated); }
Example #28
Source File: NullablePropertyFactoryTest.java From FreeBuilder with Apache License 2.0 | 5 votes |
@Test public void nullable() { TypeElement dataType = model.newType( "package com.example;", "public class DataType {", " public abstract @" + Nullable.class.getName() + " String getName();", " public static class Builder extends DataType_Builder {}", "}"); DeclaredType builderType = (DeclaredType) getOnlyElement(typesIn(dataType.getEnclosedElements())).asType(); ExecutableElement getterMethod = getOnlyElement(methodsIn(dataType.getEnclosedElements())); Property property = new Property.Builder() .setType(getterMethod.getReturnType()) .setCapitalizedName("Name") .buildPartial(); when(config.getBuilder()).thenReturn(builderType); when(config.getProperty()).thenReturn(property); when(config.getElements()).thenReturn(model.elementUtils()); doReturn(getterMethod.getAnnotationMirrors()).when(config).getAnnotations(); Optional<NullableProperty> codeGenerator = factory.create(config); assertThat(codeGenerator.get()).isEqualTo(new NullableProperty( datatype, property, ImmutableSet.of(model.typeElement(Nullable.class)), unaryOperator(model.typeMirror(String.class)))); }
Example #29
Source File: LLNI.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
protected String methodDecl(ExecutableElement method, TypeElement clazz, String cname) throws TypeSignature.SignatureException, Util.Exit { String res = null; TypeMirror retType = types.erasure(method.getReturnType()); String typesig = signature(method); TypeSignature newTypeSig = new TypeSignature(elems); String sig = newTypeSig.getTypeSignature(typesig, retType); boolean longName = needLongName(method, clazz); if (sig.charAt(0) != '(') util.error("invalid.method.signature", sig); res = "JNIEXPORT " + jniType(retType) + " JNICALL" + lineSep + jniMethodName(method, cname, longName) + "(JNIEnv *, " + cRcvrDecl(method, cname); List<? extends VariableElement> params = method.getParameters(); List<TypeMirror> argTypes = new ArrayList<TypeMirror>(); for (VariableElement p: params){ argTypes.add(types.erasure(p.asType())); } /* It would have been nice to include the argument names in the declaration, but there seems to be a bug in the "BinaryField" class, causing the getArguments() method to return "null" for most (non-constructor) methods. */ for (TypeMirror argType: argTypes) res = res + ", " + jniType(argType); res = res + ");" + lineSep; return res; }
Example #30
Source File: NameTable.java From j2objc with Apache License 2.0 | 5 votes |
/** * Return the full name of a type, including its package. For outer types, * is the type's full name; for example, java.lang.Object's full name is * "JavaLangObject". For inner classes, the full name is their outer class' * name plus the inner class name; for example, java.util.ArrayList.ListItr's * name is "JavaUtilArrayList_ListItr". */ public String getFullName(TypeElement element) { element = typeUtil.getObjcClass(element); String fullName = fullNameCache.get(element); if (fullName == null) { fullName = getFullNameImpl(element); fullNameCache.put(element, fullName); } return fullName; }