private static boolean hasAnyOfAnnotation(ExecutableElement input, List<String> annotations) { return input.getAnnotationMirrors().stream() .map(annotationMirror -> asType(annotationMirror.getAnnotationType().asElement())) .anyMatch(type -> typeInAnnotations(type, annotations)); }
roundEnv.getElementsAnnotatedWith(MoreElements.asType(customAnnotation))); DEEP_LINK_CLASS.getSimpleName()); ExecutableElement executableElement = MoreElements.asExecutable(element); TypeElement returnType = MoreTypes.asTypeElement(executableElement.getReturnType()); String qualifiedName = returnType.getQualifiedName().toString(); for (Element deepLinkHandlerElement : deepLinkHandlerElements) { Optional<AnnotationMirror> annotationMirror = getAnnotationMirror(deepLinkHandlerElement, DeepLinkHandler.class); if (annotationMirror.isPresent()) { Iterable<TypeMirror> klasses = getTypeValue(annotationMirror.get(), "value");
private void handleAnnotationMethods() { for (ExecutableElement method : ElementFilter.methodsIn(baseAnnotation.getEnclosedElements())) { elements.add(MoreElements.isAnnotationPresent(method, StringRes.class) ? modelFactory.fromStringResourceAnnotationMethod(method) : modelFactory.fromAnnotationMethod(method)); } }
/** * Returns {@code true} iff the given element has an {@link AnnotationMirror} whose * {@linkplain AnnotationMirror#getAnnotationType() annotation type} has the same canonical name * as that of {@code annotationClass}. This method is a safer alternative to calling * {@link Element#getAnnotation} and checking for {@code null} as it avoids any interaction with . This() { super(); } . This() { super(); } * annotation proxies. */ public static boolean isAnnotationPresent(Element element, Class<? extends Annotation> annotationClass) { return getAnnotationMirror(element, annotationClass).isPresent(); }
TypeElement enclosingElement = MoreElements.asType(method.getEnclosingElement()); if (!isAnnotationPresent(enclosingElement, Module.class)) { reporter.reportError("@ContributesAndroidInjector methods must be in a @Module"); getAnnotationMirror(method, ContributesAndroidInjector.class).get(); for (TypeMirror module : getAnnotationValue(annotation, "modules").accept(new AllTypesVisitor(), null)) { if (isAnnotationPresent(MoreTypes.asElement(module), Module.class)) { builder.modulesBuilder().add((ClassName) TypeName.get(module)); } else {
static Builder newBuilder(TypeElement enclosingElement) { TypeMirror typeMirror = enclosingElement.asType(); boolean isView = isSubtypeOfType(typeMirror, VIEW_TYPE); boolean isActivity = isSubtypeOfType(typeMirror, ACTIVITY_TYPE); boolean isDialog = isSubtypeOfType(typeMirror, DIALOG_TYPE); TypeName targetType = TypeName.get(typeMirror); if (targetType instanceof ParameterizedTypeName) { targetType = ((ParameterizedTypeName) targetType).rawType; } String packageName = getPackage(enclosingElement).getQualifiedName().toString(); String className = enclosingElement.getQualifiedName().toString().substring( packageName.length() + 1).replace('.', '$'); ClassName bindingClassName = ClassName.get(packageName, className + "_ViewBinding"); boolean isFinal = enclosingElement.getModifiers().contains(Modifier.FINAL); return new Builder(targetType, bindingClassName, isFinal, isView, isActivity, isDialog); }
@Override public Set<Element> process(SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) { for (Map.Entry<Class<? extends Annotation>, Element> entry : elementsByAnnotation.entries()) { AnnotationMirror annotation = getAnnotationMirror(entry.getValue(), AndroidInjectorKeyRegistry.class).get(); for (TypeMirror mapKey : getAnnotationValue(annotation, "keys").accept(new Util.AllTypesVisitor(), null)) { if (daggerSupportedTypes.containsKey(mapKey)) { messager.printMessage(Diagnostic.Kind.ERROR, String.format("%s is automatically supported", mapKey)); } if (isAnnotationPresent(MoreTypes.asElement(mapKey), MapKey.class)) { TypeMirror mapKeyValue = mapKeyValue(mapKey, elements); annotationsAndTypes.put(mapKey, mapKeyValue); } else { messager.printMessage(Diagnostic.Kind.ERROR, String.format("%s is not a @MapKey", mapKey), entry.getValue()); } } } return ImmutableSet.of(); }
return false; if (!MoreElements.methodVisibleFromPackage(overridden, MoreElements.getPackage(overrider))) { overriddenType = MoreElements.asType(overridden.getEnclosingElement());
private AutoValueExtension.Context createContext(TypeElement type) { String packageName = MoreElements.getPackage(type).getQualifiedName().toString(); Set<ExecutableElement> allMethods = MoreElements.getLocalAndInheritedMethods(type, elements); Set<ExecutableElement> methods = methodsToImplement(type, allMethods); Map<String, ExecutableElement> properties = new LinkedHashMap<String, ExecutableElement>(); for (ExecutableElement e : methods) { properties.put(e.getSimpleName().toString(), e); } return new TestContext(processingEnvironment, packageName, type, properties); }
@Override public Set<Element> process( SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) { elementsByAnnotation.forEach( (annotation, element) -> validateMethod(annotation, MoreElements.asExecutable(element))); return ImmutableSet.of(); }
private static void getLocalAndInheritedMethods( PackageElement pkg, TypeElement type, SetMultimap<String, ExecutableElement> methods) { for (TypeMirror superInterface : type.getInterfaces()) { getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(superInterface), methods); } if (type.getSuperclass().getKind() != TypeKind.NONE) { // Visit the superclass after superinterfaces so we will always see the implementation of a // method after any interfaces that declared it. getLocalAndInheritedMethods(pkg, MoreTypes.asTypeElement(type.getSuperclass()), methods); } for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) { if (!method.getModifiers().contains(Modifier.STATIC) && methodVisibleFromPackage(method, pkg)) { methods.put(method.getSimpleName().toString(), method); } } }
/** * Returns the set of all non-private methods from {@code type}, including methods that it * inherits from its ancestors. Inherited methods that are overridden are not included in the * result. So if {@code type} defines {@code public String toString()}, the returned set will * contain that method, but not the {@code toString()} method defined by {@code Object}. * * <p>The returned set may contain more than one method with the same signature, if * {@code type} inherits those methods from different ancestors. For example, if it * inherits from unrelated interfaces {@code One} and {@code Two} which each define * {@code void foo();}, and if it does not itself override the {@code foo()} method, * then both {@code One.foo()} and {@code Two.foo()} will be in the returned set. * * @param type the type whose own and inherited methods are to be returned * @param elementUtils an {@link Elements} object, typically returned by * {@link javax.annotation.processing.AbstractProcessor#processingEnv processingEnv}<!-- * -->.{@link javax.annotation.processing.ProcessingEnvironment#getElementUtils * getElementUtils()} * * @deprecated The method {@link #getLocalAndInheritedMethods(TypeElement, Types, Elements)} * has better consistency between Java compilers. */ @Deprecated public static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Elements elementUtils) { Overrides overrides = new Overrides.NativeOverrides(elementUtils); return getLocalAndInheritedMethods(type, overrides); }
private <A extends Annotation> void printMessages(Class<A> annotationType, Set<? extends Element> elements, Diagnostic.Kind kind, Function<? super A, String> value) { for (Element element : elements) { A annotation = element.getAnnotation(annotationType); AnnotationMirror mirror = MoreElements.getAnnotationMirror(element, annotationType).get(); processingEnv.getMessager().printMessage(kind, value.apply(annotation), element, mirror); } } });
.build(); String packageName = MoreElements.getPackage(type).getQualifiedName().toString(); String className = String.format("%sAdapter", type.getSimpleName()); TypeSpec adapterClass = TypeSpec.classBuilder(className)
private static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Overrides overrides) { SetMultimap<String, ExecutableElement> methodMap = LinkedHashMultimap.create(); getLocalAndInheritedMethods(getPackage(type), type, methodMap); // Find methods that are overridden. We do this using `Elements.overrides`, which means // that it is inherently a quadratic operation, since we have to compare every method against // every other method. We reduce the performance impact by (a) grouping methods by name, since // a method cannot override another method with a different name, and (b) making sure that // methods in ancestor types precede those in descendant types, which means we only have to // check a method against the ones that follow it in that order. Set<ExecutableElement> overridden = new LinkedHashSet<ExecutableElement>(); for (Collection<ExecutableElement> methods : methodMap.asMap().values()) { List<ExecutableElement> methodList = ImmutableList.copyOf(methods); for (int i = 0; i < methodList.size(); i++) { ExecutableElement methodI = methodList.get(i); for (int j = i + 1; j < methodList.size(); j++) { ExecutableElement methodJ = methodList.get(j); if (overrides.overrides(methodJ, methodI, type)) { overridden.add(methodI); } } } } Set<ExecutableElement> methods = new LinkedHashSet<ExecutableElement>(methodMap.values()); methods.removeAll(overridden); return ImmutableSet.copyOf(methods); }
/** * Resolves a {@link VariableElement} parameter to a method or constructor based on the given * container, or a member of a class. For parameters to a method or constructor, the variable's * enclosing element must be a supertype of the container type. For example, given a * {@code container} of type {@code Set<String>}, and a variable corresponding to the {@code E e} * parameter in the {@code Set.add(E e)} method, this will return a TypeMirror for {@code String}. */ public static TypeMirror asMemberOf(Types types, DeclaredType container, VariableElement variable) { if (variable.getKind().equals(ElementKind.PARAMETER)) { ExecutableElement methodOrConstructor = MoreElements.asExecutable(variable.getEnclosingElement()); ExecutableType resolvedMethodOrConstructor = MoreTypes.asExecutable(types.asMemberOf(container, methodOrConstructor)); List<? extends VariableElement> parameters = methodOrConstructor.getParameters(); List<? extends TypeMirror> parameterTypes = resolvedMethodOrConstructor.getParameterTypes(); checkState(parameters.size() == parameterTypes.size()); for (int i = 0; i < parameters.size(); i++) { // We need to capture the parameter type of the variable we're concerned about, // for later printing. This is the only way to do it since we can't use // types.asMemberOf on variables of methods. if (parameters.get(i).equals(variable)) { return parameterTypes.get(i); } } throw new IllegalStateException("Could not find variable: " + variable); } else { return types.asMemberOf(container, variable); } }
/** * Returns the set of all non-private methods from {@code type}, including methods that it * inherits from its ancestors. Inherited methods that are overridden are not included in the * result. So if {@code type} defines {@code public String toString()}, the returned set will * contain that method, but not the {@code toString()} method defined by {@code Object}. * * <p>The returned set may contain more than one method with the same signature, if * {@code type} inherits those methods from different ancestors. For example, if it * inherits from unrelated interfaces {@code One} and {@code Two} which each define * {@code void foo();}, and if it does not itself override the {@code foo()} method, * then both {@code One.foo()} and {@code Two.foo()} will be in the returned set. * * @param type the type whose own and inherited methods are to be returned * @param typeUtils a {@link Types} object, typically returned by * {@link javax.annotation.processing.AbstractProcessor#processingEnv processingEnv}<!-- * -->.{@link javax.annotation.processing.ProcessingEnvironment#getTypeUtils * getTypeUtils()} * @param elementUtils an {@link Elements} object, typically returned by * {@link javax.annotation.processing.AbstractProcessor#processingEnv processingEnv}<!-- * -->.{@link javax.annotation.processing.ProcessingEnvironment#getElementUtils * getElementUtils()} */ public static ImmutableSet<ExecutableElement> getLocalAndInheritedMethods( TypeElement type, Types typeUtils, Elements elementUtils) { // TODO(emcmanus): detect if the Types and Elements are the javac ones, and use // NativeOverrides if so. We may need to adjust the logic further to avoid the bug // tested for by MoreElementsTest.getLocalAndInheritedMethods_DaggerBug. Overrides overrides = new Overrides.ExplicitOverrides(typeUtils); return getLocalAndInheritedMethods(type, overrides); }
@Override public boolean process(@Nullable Set<? extends TypeElement> annotations, @NonNull RoundEnvironment roundEnv) { try { final ArrayList<? extends Element> annotatedElements = new ArrayList<>(roundEnv.getElementsAnnotatedWith(Configuration.class)); if (!annotatedElements.isEmpty()) { for (final Element e : annotatedElements) { if (e.getKind() == ElementKind.ANNOTATION_TYPE) { new ClassCreator(MoreElements.asType(e), e.getAnnotation(Configuration.class), processingEnv).createClasses(); } else { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, String.format("%s is only supported on %s", Configuration.class.getName(), ElementKind.ANNOTATION_TYPE.name()), e); } } } } catch (Exception e) { e.printStackTrace(); processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed to generate acra classes"); } return true; }
public String resolve(VariableElement element) { AnnotationMirror annotationMirror = getAnnotationMirror(element, getAssociatedClass()).get(); Collection<? extends AnnotationValue> values = filterKeys(annotationMirror.getElementValues(), new Predicate<ExecutableElement>() { @Override public boolean apply(ExecutableElement executableElement) { return executableElement.getSimpleName().contentEquals("value"); } }).values(); return Iterables.getOnlyElement(values).getValue().toString(); } }
private static boolean annotatedWithAutoFactory(Element e) { return isAnnotationPresent(e, AutoFactory.class); } }