javax.lang.model.util.Elements Java Examples
The following examples show how to use
javax.lang.model.util.Elements.
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: DefaultSourceOnlyAbiRuleInfo.java From buck with Apache License 2.0 | 6 votes |
@Nullable private String getOwningTarget( Elements elements, Element element, ImmutableList<JavaAbiInfo> classpath) { TypeElement enclosingType = MoreElements.getTypeElement(element); String classFilePath = elements.getBinaryName(enclosingType).toString().replace('.', File.separatorChar) + ".class"; for (JavaAbiInfo info : classpath) { if (info.jarContains(classFilePath)) { return info.getBuildTarget().getUnflavoredBuildTarget().toString(); } } return null; }
Example #2
Source File: InterfaceValidator.java From buck with Apache License 2.0 | 6 votes |
public ValidatingListener( Diagnostic.Kind messageKind, Elements elements, Types types, Trees trees, SourceOnlyAbiRuleInfo ruleInfo, FileManagerSimulator fileManager, CompilerTypeResolutionSimulator compilerResolver, CompilationUnitTree compilationUnit) { this.messageKind = messageKind; this.trees = trees; this.ruleInfo = ruleInfo; this.fileManager = fileManager; this.compilerResolver = compilerResolver; completer = new CompletionSimulator(fileManager); imports = new ImportsTracker( elements, types, (PackageElement) Objects.requireNonNull(trees.getElement(new TreePath(compilationUnit)))); treeBackedResolver = new TreeBackedTypeResolutionSimulator(elements, trees, compilationUnit); }
Example #3
Source File: BuilderContextManager.java From sundrio with Apache License 2.0 | 6 votes |
public static BuilderContext create(Elements elements, Types types, Boolean validationEnabled, Boolean generateBuilderPackage, String packageName, Inline... inlineables) { if (context == null) { context = new BuilderContext(elements, types, generateBuilderPackage, validationEnabled, packageName, inlineables); return context; } else { if (!packageName.equals(context.getBuilderPackage())) { throw new IllegalStateException("Cannot use different builder package names in a single project. Used:" + packageName + " but package:" + context.getGenerateBuilderPackage() + " already exists."); } else if (!generateBuilderPackage.equals(context.getGenerateBuilderPackage())) { throw new IllegalStateException("Cannot use different values for generate builder package in a single project."); } else { return context; } } }
Example #4
Source File: AnnotationUtility.java From kripton with Apache License 2.0 | 6 votes |
/** * Extract from an annotation of a method the attribute value specified. IF NO ELEMENT WAS FOUND, AN EMPTY LIST WILL RETURN. * * @param item the item * @param annotationClass the annotation class * @param attributeName the attribute name * @return attribute value extracted as class typeName */ public static List<String> extractAsStringArray(Element item, Class<? extends Annotation> annotationClass, AnnotationAttributeType attributeName) { final Elements elementUtils=BaseProcessor.elementUtils; final One<List<String>> result = new One<List<String>>(new ArrayList<String>()); extractString(elementUtils, item, annotationClass, attributeName, new OnAttributeFoundListener() { @Override public void onFound(String value) { List<String> list = AnnotationUtility.extractAsArrayOfString(value); result.value0 = list; } }); return result.value0; }
Example #5
Source File: ClassEntity.java From RxPay with Apache License 2.0 | 6 votes |
/** * @param elementUtils * @param typeUtils * @param element current anntated class */ public ClassEntity(Elements elementUtils, Types typeUtils, TypeElement element) { elementWeakCache = new WeakReference<TypeElement>(element); this.classPackageName = elementUtils.getPackageOf(element).getQualifiedName().toString(); this.modifierSet = element.getModifiers(); this.className = element.toString(); annotationMirrors = element.getAnnotationMirrors(); this.classSimpleName = element.getSimpleName(); this.classQualifiedName = element.getQualifiedName(); if ("java.lang.Object".equals(element.getSuperclass().toString())){ this.superclass = null; }else{ this.superclass = element.getSuperclass().toString(); } List<? extends TypeMirror> interfaces = element.getInterfaces(); for (TypeMirror anInterface : interfaces){ this.interfaces.add(typeUtils.asElement(anInterface).toString()); } }
Example #6
Source File: ModuleInfo.java From vertx-codegen with Apache License 2.0 | 6 votes |
public static DeclaredType resolveJsonMapper(Elements elementUtils, Types typeUtils, PackageElement pkgElt, DeclaredType javaType) { PackageElement result = resolveFirstModuleGenAnnotatedPackageElement(elementUtils, pkgElt); if (result != null) { TypeElement jsonMapperElt = elementUtils.getTypeElement("io.vertx.core.spi.json.JsonMapper"); TypeParameterElement typeParamElt = jsonMapperElt.getTypeParameters().get(0); return elementUtils .getAllAnnotationMirrors(pkgElt) .stream() .filter(am -> am.getAnnotationType().toString().equals(ModuleGen.class.getName())) .flatMap(am -> am.getElementValues().entrySet().stream()) .filter(e -> e.getKey().getSimpleName().toString().equals("mappers")) .flatMap(e -> ((List<AnnotationValue>) e.getValue().getValue()).stream()) .map(annotationValue -> (DeclaredType) annotationValue.getValue()) .filter(dt -> { TypeMirror mapperType = Helper.resolveTypeParameter(typeUtils, dt, typeParamElt); return mapperType != null && mapperType.getKind() == TypeKind.DECLARED && typeUtils.isSameType(mapperType, javaType); }) .findFirst() .orElse(null); } return null; }
Example #7
Source File: ProcessorUtils.java From bazel with Apache License 2.0 | 6 votes |
/** * Returns the contents of a {@code Class}-typed field in an annotation. * * <p>Taken & adapted from AutoValueProcessor.java * * <p>This method is needed because directly reading the value of such a field from an * AnnotationMirror throws: * * <pre> * javax.lang.model.type.MirroredTypeException: Attempt to access Class object for TypeMirror Foo. * </pre> * * @param annotation The annotation to read from. * @param fieldName The name of the field to read, e.g. "exclude". * @return a set of fully-qualified names of classes appearing in 'fieldName' on 'annotation' on * 'element'. */ static TypeElement getClassTypeFromAnnotationField( Elements elementUtils, AnnotationMirror annotation, String fieldName) throws OptionProcessorException { for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : elementUtils.getElementValuesWithDefaults(annotation).entrySet()) { if (entry.getKey().getSimpleName().contentEquals(fieldName)) { Object annotationField = entry.getValue().getValue(); if (!(annotationField instanceof DeclaredType)) { throw new IllegalStateException( String.format( "The fieldName provided should only apply to Class<> type annotation fields, " + "but the field's value (%s) couldn't get cast to a DeclaredType", entry)); } String qualifiedName = ((TypeElement) ((DeclaredType) annotationField).asElement()) .getQualifiedName() .toString(); return elementUtils.getTypeElement(qualifiedName); } } // Annotation missing the requested field. throw new OptionProcessorException( null, "No member %s of the %s annotation found for element.", fieldName, annotation); }
Example #8
Source File: ElementUtilities.java From netbeans with Apache License 2.0 | 6 votes |
private boolean isHidden(Element member, List<? extends Element> members, Elements elements, Types types) { for (ListIterator<? extends Element> it = members.listIterator(); it.hasNext();) { Element hider = it.next(); if (hider == member) return true; if (hider.getSimpleName().contentEquals(member.getSimpleName())) { if (elements.hides(member, hider)) { it.remove(); } else { if (member instanceof VariableElement && hider instanceof VariableElement && (!member.getKind().isField() || hider.getKind().isField())) return true; TypeMirror memberType = member.asType(); TypeMirror hiderType = hider.asType(); if (memberType.getKind() == TypeKind.EXECUTABLE && hiderType.getKind() == TypeKind.EXECUTABLE) { if (types.isSubsignature((ExecutableType)hiderType, (ExecutableType)memberType)) return true; } else { return false; } } } } return false; }
Example #9
Source File: PluginProcessor.java From logging-log4j2 with Apache License 2.0 | 6 votes |
private String calculatePackage(Elements elements, Element element, String packageName) { Name name = elements.getPackageOf(element).getQualifiedName(); if (name == null) { return null; } String pkgName = name.toString(); if (packageName == null) { return pkgName; } if (pkgName.length() == packageName.length()) { return packageName; } if (pkgName.length() < packageName.length() && packageName.startsWith(pkgName)) { return pkgName; } return commonPrefix(pkgName, packageName); }
Example #10
Source File: ProbingEnvironment.java From revapi with Apache License 2.0 | 5 votes |
@Nonnull @Override public Elements getElementUtils() { if (processingEnvironment == null) { throw new IllegalStateException("Types instance not yet available. It is too early to call this method." + " Wait until after the archives are visited and the API model constructed."); } return new MissingTypeAwareDelegatingElements(processingEnvironment.getElementUtils()); }
Example #11
Source File: EntRefContainerImpl.java From netbeans with Apache License 2.0 | 5 votes |
private void writeDD(FileObject referencingFile, final String referencingClass) throws IOException { WebModuleImpl jp = project.getLookup().lookup(WebModuleProviderImpl.class).getModuleImpl(); // test if referencing class is injection target final boolean[] isInjectionTarget = {false}; CancellableTask<CompilationController> task = new CancellableTask<CompilationController>() { @Override public void run(CompilationController controller) throws IOException { Elements elements = controller.getElements(); TypeElement thisElement = elements.getTypeElement(referencingClass); if (thisElement!=null) isInjectionTarget[0] = InjectionTargetQuery.isInjectionTarget(controller, thisElement); } @Override public void cancel() {} }; JavaSource refFile = JavaSource.forFileObject(referencingFile); if (refFile!=null) { refFile.runUserActionTask(task, true); } boolean shouldWrite = isDescriptorMandatory(jp.getJ2eeProfile()) || !isInjectionTarget[0]; if (shouldWrite) { FileObject fo = jp.getDeploymentDescriptor(); getWebApp().write(fo); } }
Example #12
Source File: T6358786.java From hottub with GNU General Public License v2.0 | 5 votes |
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); } }
Example #13
Source File: TestMethodNameGenerator.java From netbeans with Apache License 2.0 | 5 votes |
/** * Collects names of accessible no-argument methods that are present * in the given class and its superclasses. Methods inherited from the * class's superclasses are taken into account, too. * * @param clazz class whose methods' names should be collected * @param reservedMethodNames collection to which the method names * should be added */ private void collectExistingMethodNames(TypeElement clazz, Collection<String> reservedMethodNames) { final Elements elements = workingCopy.getElements(); List<? extends Element> allMembers = elements.getAllMembers(clazz); List<? extends ExecutableElement> methods = ElementFilter.methodsIn(allMembers); if (!methods.isEmpty()) { for (ExecutableElement method : methods) { if (method.getParameters().isEmpty()) { reservedMethodNames.add(method.getSimpleName().toString()); } } } }
Example #14
Source File: ConfiguredObjectRegistrationGenerator.java From qpid-broker-j with Apache License 2.0 | 5 votes |
@Override public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) { if (!_elementProcessingDone) { final Elements elementUtils = processingEnv.getElementUtils(); final TypeElement managedObjectElement = elementUtils.getTypeElement(MANAGED_OBJECT_CANONICAL_NAME); try { roundEnv.getElementsAnnotatedWith(managedObjectElement).stream() .map(element -> elementUtils.getPackageOf(element)) .flatMap(packageElement -> packageElement.getEnclosedElements().stream()) .filter(element -> hasAnnotation(element, managedObjectElement)) .forEach(annotatedElement -> processAnnotatedElement(elementUtils, managedObjectElement, annotatedElement)); for (Map.Entry<String, Set<String>> entry : _managedObjectClasses.entrySet()) { processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, String.format("Generating CO registration for package '%s'", entry.getKey())); generateRegistrationFile(entry.getKey(), entry.getValue()); } _managedObjectClasses.clear(); _typeMap.clear(); _categoryMap.clear(); _elementProcessingDone = true; } catch (Exception e) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error: " + e.getLocalizedMessage()); } } return false; }
Example #15
Source File: CompilationRuleTest.java From compile-testing with Apache License 2.0 | 5 votes |
/** * 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 #16
Source File: ModelUtils.java From FreeBuilder with Apache License 2.0 | 5 votes |
/** * Returns the upper bound of {@code type}.<ul> * <li>T -> T * <li>? -> Object * <li>? extends T -> T * <li>? super T -> Object * </ul> */ public static TypeMirror upperBound(Elements elements, TypeMirror type) { if (type.getKind() == TypeKind.WILDCARD) { WildcardType wildcard = (WildcardType) type; type = wildcard.getExtendsBound(); if (type == null) { type = elements.getTypeElement(Object.class.getName()).asType(); } } return type; }
Example #17
Source File: Env.java From hottub with GNU General Public License v2.0 | 5 votes |
void init(DocTrees trees, Elements elements, Types types) { this.trees = trees; this.elements = elements; this.types = types; java_lang_Error = elements.getTypeElement("java.lang.Error").asType(); java_lang_RuntimeException = elements.getTypeElement("java.lang.RuntimeException").asType(); java_lang_Throwable = elements.getTypeElement("java.lang.Throwable").asType(); java_lang_Void = elements.getTypeElement("java.lang.Void").asType(); }
Example #18
Source File: AnnotationUtility.java From kripton with Apache License 2.0 | 5 votes |
/** * Extract from an annotation of a method the attribute value specified. * * @param method method to analyze * @param annotationClass annotation to analyze * @param attribute the attribute * @return attribute value as list of string */ public static List<String> extractAsStringArray(ModelMethod method, ModelAnnotation annotationClass, AnnotationAttributeType attribute) { final Elements elementUtils=BaseProcessor.elementUtils; final One<List<String>> result = new One<List<String>>(); extractAttributeValue(elementUtils, method.getElement(), annotationClass.getName(), attribute, new OnAttributeFoundListener() { @Override public void onFound(String value) { result.value0 = AnnotationUtility.extractAsArrayOfString(value); } }); return result.value0; }
Example #19
Source File: SortedSetProperty.java From FreeBuilder with Apache License 2.0 | 5 votes |
private static TypeMirror wildcardSuperSortedSet( TypeMirror elementType, Elements elements, Types types) { TypeElement setType = elements.getTypeElement(SortedSet.class.getName()); return types.getWildcardType(null, types.getDeclaredType(setType, elementType)); }
Example #20
Source File: ElementSearch.java From netbeans with Apache License 2.0 | 5 votes |
@CheckForNull public static TypeElement getClass(Elements elements, String name) { TypeElement typeElement = elements.getTypeElement(name); if (typeElement == null) { typeElement = getInnerClass(elements, name); } return typeElement; }
Example #21
Source File: Nodes.java From netbeans with Apache License 2.0 | 5 votes |
@CheckForNull private static FileObject findBinaryInCp( @NonNull final Elements elements, @NonNull final TypeElement element, @NonNull final ClassPath cp) { final FileObject file = cp.findResource(String.format( "%s.class", //NOI18N elements.getBinaryName(element).toString().replace('.', '/'))); //NOI18N return file == null ? null : cp.findOwnerRoot(file); }
Example #22
Source File: MapProperty.java From FreeBuilder with Apache License 2.0 | 5 votes |
private static TypeMirror wildcardSuperMap( TypeMirror keyType, TypeMirror valueType, Elements elements, Types types) { TypeElement mapType = elements.getTypeElement(Map.class.getName()); return types.getWildcardType(null, types.getDeclaredType(mapType, keyType, valueType)); }
Example #23
Source File: ExtensionTest.java From auto with Apache License 2.0 | 5 votes |
@Test public void testCantConsumeNonExistentMethod() { 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();", "}"); Compilation compilation = javac() .withProcessors(new AutoValueProcessor(ImmutableList.of(new ConsumeBogusMethod()))) .compile(impl); assertThat(compilation) .hadErrorContainingMatch( "wants to consume a method that is not one of the abstract methods in this class" + ".*intValue\\(\\)") .inFile(impl) .onLineContaining("@AutoValue public abstract class Baz"); }
Example #24
Source File: ExtraInjectorClassBuilder.java From PrettyBundle with Apache License 2.0 | 5 votes |
private MethodSpec buildInjectMethod(Elements elementUtils) { final MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("inject") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC) .addParameter(TypeVariableName.get(extraClassesGrouped.getExtraAnnotatedClassName()), "target") .addParameter(Androids.bundleClass(), "extras"); addInjectStatement(methodBuilder, "target", elementUtils); return methodBuilder .build(); }
Example #25
Source File: FactoryCodeBuilder.java From ShapeView with Apache License 2.0 | 5 votes |
public void generateCode(Messager messager, Elements elementUtils, Filer filer) throws IOException { TypeElement superClassName = elementUtils.getTypeElement(mSupperClsName); String factoryClassName = superClassName.getSimpleName() + SUFFIX; PackageElement pkg = elementUtils.getPackageOf(superClassName); String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString(); TypeSpec typeSpec = TypeSpec .classBuilder(factoryClassName) .addModifiers(Modifier.PUBLIC) .addMethod(newCreateMethod(elementUtils, superClassName)) .build(); // Write file JavaFile.builder(packageName, typeSpec).build().writeTo(filer); }
Example #26
Source File: MembersInjectorGenerator.java From dagger2-sample with Apache License 2.0 | 5 votes |
MembersInjectorGenerator( Filer filer, Elements elements, Types types, DependencyRequestMapper dependencyRequestMapper) { super(filer); this.elements = checkNotNull(elements); this.types = checkNotNull(types); this.dependencyRequestMapper = dependencyRequestMapper; }
Example #27
Source File: JFXProjectUtils.java From netbeans with Apache License 2.0 | 5 votes |
/** * Returns set of names of classes of the classType type. * * @param classpathMap map of classpaths of all project files * @param classType return only classes of this type * @return set of class names */ public static Set<String> getAppClassNames(@NonNull Collection<? extends FileObject> roots, final @NonNull String classType) { final Set<String> appClassNames = new HashSet<>(); for (FileObject fo : roots) { final ClasspathInfo cpInfo = ClasspathInfo.create(fo); final JavaSource js = JavaSource.create(cpInfo); if (js != null) { try { js.runUserActionTask(new Task<CompilationController>() { @Override public void run(CompilationController controller) throws Exception { final ClassIndex classIndex = cpInfo.getClassIndex(); final Elements elems = controller.getElements(); TypeElement fxAppElement = elems.getTypeElement(classType); ElementHandle<TypeElement> appHandle = ElementHandle.create(fxAppElement); Set<ElementHandle<TypeElement>> appHandles = classIndex.getElements(appHandle, kinds, scopes); for (ElementHandle<TypeElement> elemHandle : appHandles) { appClassNames.add(elemHandle.getQualifiedName()); } } }, true); } catch (Exception e) { } } } return appClassNames; }
Example #28
Source File: ElementOverlay.java From netbeans with Apache License 2.0 | 5 votes |
private Collection<? extends Element> getAllMembers(ASTService ast, Elements elements, Element el) { List<Element> result = new ArrayList<Element>(); result.addAll(el.getEnclosedElements()); for (Element parent : getAllSuperElements(ast, elements, el)) { if (!el.equals(parent)) { result.addAll(getAllMembers(ast, elements, parent)); } } return result; }
Example #29
Source File: TypeSimplifier.java From auto with Apache License 2.0 | 5 votes |
/** * Handles the tricky case where the class being referred to is in {@code java.lang}, but the * package of the referring code contains another class of the same name. For example, if the * current package is {@code foo.bar} and there is a {@code foo.bar.Compiler}, then we will refer * to {@code java.lang.Compiler} by its full name. The plain name {@code Compiler} would reference * {@code foo.bar.Compiler} in this case. We need to write {@code java.lang.Compiler} even if the * other {@code Compiler} class is not being considered here, so the {@link #ambiguousNames} logic * is not enough. We have to look to see if the class exists. */ private static String javaLangSpelling( Elements elementUtils, String codePackageName, TypeElement typeElement) { // If this is java.lang.Thread.State or the like, we have to look for a clash with Thread. TypeElement topLevelType = topLevelType(typeElement); TypeElement clash = elementUtils.getTypeElement(codePackageName + "." + topLevelType.getSimpleName()); String fullName = typeElement.getQualifiedName().toString(); return (clash == null) ? fullName.substring("java.lang.".length()) : fullName; }
Example #30
Source File: Utils.java From paperparcel with Apache License 2.0 | 5 votes |
/** Returns true if {@code element} is a {@code TypeAdapter} type. */ static boolean isAdapterType(Element element, Elements elements, Types types) { TypeMirror typeAdapterType = types.getDeclaredType( elements.getTypeElement(TYPE_ADAPTER_CLASS_NAME), types.getWildcardType(null, null)); return types.isAssignable(element.asType(), typeAdapterType); }