Java Code Examples for com.google.auto.common.MoreElements#asType()
The following examples show how to use
com.google.auto.common.MoreElements#asType() .
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: ConfigurationAnnotations.java From dagger2-sample with Apache License 2.0 | 6 votes |
/** Traverses includes from superclasses and adds them into the builder. */ private static void addIncludesFromSuperclasses(Types types, TypeElement element, ImmutableSet.Builder<TypeElement> builder, TypeMirror objectType) { // Also add the superclass to the queue, in case any @Module definitions were on that. TypeMirror superclass = element.getSuperclass(); while (!types.isSameType(objectType, superclass) && superclass.getKind().equals(TypeKind.DECLARED)) { element = MoreElements.asType(types.asElement(superclass)); Optional<AnnotationMirror> moduleMirror = getAnnotationMirror(element, Module.class) .or(getAnnotationMirror(element, ProducerModule.class)); if (moduleMirror.isPresent()) { builder.addAll(MoreTypes.asTypeElements(getModuleIncludes(moduleMirror.get()))); } superclass = element.getSuperclass(); } }
Example 2
Source File: BuilderSpec.java From RetroFacebook with Apache License 2.0 | 6 votes |
private void addAbstractMethods( TypeMirror typeMirror, List<ExecutableElement> abstractMethods) { if (typeMirror.getKind() != TypeKind.DECLARED) { return; } TypeElement typeElement = MoreElements.asType(typeMirror.accept(AS_ELEMENT_VISITOR, null)); addAbstractMethods(typeElement.getSuperclass(), abstractMethods); for (TypeMirror interfaceMirror : typeElement.getInterfaces()) { addAbstractMethods(interfaceMirror, abstractMethods); } for (ExecutableElement method : ElementFilter.methodsIn(typeElement.getEnclosedElements())) { for (Iterator<ExecutableElement> it = abstractMethods.iterator(); it.hasNext(); ) { ExecutableElement maybeOverridden = it.next(); if (elementUtils.overrides(method, maybeOverridden, typeElement)) { it.remove(); } } if (method.getModifiers().contains(Modifier.ABSTRACT)) { abstractMethods.add(method); } } }
Example 3
Source File: BuilderSpec.java From RetroFacebook with Apache License 2.0 | 6 votes |
private void addAbstractMethods( TypeMirror typeMirror, List<ExecutableElement> abstractMethods) { if (typeMirror.getKind() != TypeKind.DECLARED) { return; } TypeElement typeElement = MoreElements.asType(typeMirror.accept(AS_ELEMENT_VISITOR, null)); addAbstractMethods(typeElement.getSuperclass(), abstractMethods); for (TypeMirror interfaceMirror : typeElement.getInterfaces()) { addAbstractMethods(interfaceMirror, abstractMethods); } for (ExecutableElement method : ElementFilter.methodsIn(typeElement.getEnclosedElements())) { for (Iterator<ExecutableElement> it = abstractMethods.iterator(); it.hasNext(); ) { ExecutableElement maybeOverridden = it.next(); if (elementUtils.overrides(method, maybeOverridden, typeElement)) { it.remove(); } } if (method.getModifiers().contains(Modifier.ABSTRACT)) { abstractMethods.add(method); } } }
Example 4
Source File: ComponentProcessingStep.java From dagger2-sample with Apache License 2.0 | 6 votes |
@Override public void process(SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) { Set<? extends Element> componentElements = elementsByAnnotation.get(Component.class); for (Element element : componentElements) { TypeElement componentTypeElement = MoreElements.asType(element); ValidationReport<TypeElement> componentReport = componentValidator.validate(componentTypeElement); componentReport.printMessagesTo(messager); if (componentReport.isClean()) { ComponentDescriptor componentDescriptor = componentDescriptorFactory.forComponent(componentTypeElement); BindingGraph bindingGraph = bindingGraphFactory.create(componentDescriptor); ValidationReport<BindingGraph> graphReport = bindingGraphValidator.validate(bindingGraph); graphReport.printMessagesTo(messager); if (graphReport.isClean()) { try { componentGenerator.generate(bindingGraph); } catch (SourceFileGenerationException e) { e.printMessageTo(messager); } } } } }
Example 5
Source File: InjectBindingRegistry.java From dagger2-sample with Apache License 2.0 | 5 votes |
Optional<ProvisionBinding> getOrFindProvisionBinding(Key key) { checkNotNull(key); if (!key.isValidImplicitProvisionKey(types)) { return Optional.absent(); } ProvisionBinding binding = provisionBindings.getBinding(key); if (binding != null) { return Optional.of(binding); } // ok, let's see if we can find an @Inject constructor TypeElement element = MoreElements.asType(types.asElement(key.type())); List<ExecutableElement> constructors = ElementFilter.constructorsIn(element.getEnclosedElements()); ImmutableSet<ExecutableElement> injectConstructors = FluentIterable.from(constructors) .filter(new Predicate<ExecutableElement>() { @Override public boolean apply(ExecutableElement input) { return isAnnotationPresent(input, Inject.class); } }).toSet(); switch (injectConstructors.size()) { case 0: // No constructor found. return Optional.absent(); case 1: ProvisionBinding constructorBinding = provisionBindingFactory.forInjectConstructor( Iterables.getOnlyElement(injectConstructors), Optional.of(key.type())); return Optional.of(registerBinding(constructorBinding, false)); default: throw new IllegalStateException("Found multiple @Inject constructors: " + injectConstructors); } }
Example 6
Source File: ComponentProcessingStep.java From bullet with Apache License 2.0 | 5 votes |
@Override public void process(SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) { Set<Element> componentElements = Sets.union( elementsByAnnotation.get(Component.class), elementsByAnnotation.get(Subcomponent.class)); for (Element element : componentElements) { TypeElement componentElement = MoreElements.asType(element); generateObjectGraph(componentElement); } }
Example 7
Source File: FactoryDescriptorGenerator.java From auto with Apache License 2.0 | 5 votes |
FactoryMethodDescriptor generateDescriptorForConstructor(final AutoFactoryDeclaration declaration, ExecutableElement constructor) { checkNotNull(constructor); checkArgument(constructor.getKind() == ElementKind.CONSTRUCTOR); TypeElement classElement = MoreElements.asType(constructor.getEnclosingElement()); ImmutableListMultimap<Boolean, ? extends VariableElement> parameterMap = Multimaps.index(constructor.getParameters(), Functions.forPredicate( new Predicate<VariableElement>() { @Override public boolean apply(VariableElement parameter) { return isAnnotationPresent(parameter, Provided.class); } })); ImmutableSet<Parameter> providedParameters = Parameter.forParameterList(parameterMap.get(true), types); ImmutableSet<Parameter> passedParameters = Parameter.forParameterList(parameterMap.get(false), types); return FactoryMethodDescriptor.builder(declaration) .name("create") .returnType(classElement.asType()) .publicMethod(classElement.getModifiers().contains(PUBLIC)) .providedParameters(providedParameters) .passedParameters(passedParameters) .creationParameters(Parameter.forParameterList(constructor.getParameters(), types)) .isVarArgs(constructor.isVarArgs()) .build(); }
Example 8
Source File: EclipseHack.java From auto with Apache License 2.0 | 5 votes |
/** * Constructs a map from name to method of the no-argument methods in the given type. We need this * because an ExecutableElement returned by {@link Elements#getAllMembers} will not compare equal * to the original ExecutableElement if {@code getAllMembers} substituted type parameters, as it * does in Eclipse. */ private Map<Name, ExecutableElement> noArgMethodsIn(DeclaredType in) { TypeElement autoValueType = MoreElements.asType(typeUtils.asElement(in)); List<ExecutableElement> allMethods = ElementFilter.methodsIn(elementUtils.getAllMembers(autoValueType)); Map<Name, ExecutableElement> map = new LinkedHashMap<Name, ExecutableElement>(); for (ExecutableElement method : allMethods) { if (method.getParameters().isEmpty()) { map.put(method.getSimpleName(), method); } } return map; }
Example 9
Source File: MethodSignatureFormatter.java From dagger2-sample with Apache License 2.0 | 5 votes |
/** * Formats an ExecutableElement as if it were contained within the container, if the container is * present. */ public String format(ExecutableElement method, Optional<DeclaredType> container) { StringBuilder builder = new StringBuilder(); TypeElement type = MoreElements.asType(method.getEnclosingElement()); ExecutableType executableType = MoreTypes.asExecutable(method.asType()); if (container.isPresent()) { executableType = MoreTypes.asExecutable(types.asMemberOf(container.get(), method)); type = MoreElements.asType(container.get().asElement()); } // TODO(cgruber): AnnotationMirror formatter. List<? extends AnnotationMirror> annotations = method.getAnnotationMirrors(); if (!annotations.isEmpty()) { Iterator<? extends AnnotationMirror> annotationIterator = annotations.iterator(); for (int i = 0; annotationIterator.hasNext(); i++) { if (i > 0) { builder.append(' '); } builder.append(ErrorMessages.format(annotationIterator.next())); } builder.append(' '); } builder.append(nameOfType(executableType.getReturnType())); builder.append(' '); builder.append(type.getQualifiedName()); builder.append('.'); builder.append(method.getSimpleName()); builder.append('('); checkState(method.getParameters().size() == executableType.getParameterTypes().size()); Iterator<? extends VariableElement> parameters = method.getParameters().iterator(); Iterator<? extends TypeMirror> parameterTypes = executableType.getParameterTypes().iterator(); for (int i = 0; parameters.hasNext(); i++) { if (i > 0) { builder.append(", "); } appendParameter(builder, parameters.next(), parameterTypes.next()); } builder.append(')'); return builder.toString(); }
Example 10
Source File: ProvisionBinding.java From dagger2-sample with Apache License 2.0 | 5 votes |
private Optional<DependencyRequest> membersInjectionRequest(DeclaredType type) { TypeElement typeElement = MoreElements.asType(type.asElement()); if (!types.isSameType(elements.getTypeElement(Object.class.getCanonicalName()).asType(), typeElement.getSuperclass())) { return Optional.of(dependencyRequestFactory.forMembersInjectedType(type)); } for (Element enclosedElement : typeElement.getEnclosedElements()) { if (MEMBER_KINDS.contains(enclosedElement.getKind()) && (isAnnotationPresent(enclosedElement, Inject.class))) { return Optional.of(dependencyRequestFactory.forMembersInjectedType(type)); } } return Optional.absent(); }
Example 11
Source File: J2clAstProcessor.java From j2cl with Apache License 2.0 | 5 votes |
Field(String name, TypeMirror type, boolean isNullable) { this.name = name; this.isNullable = isNullable; TypeElement typeElement = MoreElements.asType(MoreTypes.asElement(type)); if (typeElement.getQualifiedName().contentEquals("java.util.List")) { this.type = Type.LIST; this.componentTypeName = MoreTypes.asElement(MoreTypes.asDeclared(type).getTypeArguments().get(0)) .getSimpleName() .toString(); } else { this.type = Type.SCALAR; } this.typeName = typeElement.getSimpleName().toString(); }
Example 12
Source File: AdditionExtractor.java From Auto-Dagger2 with MIT License | 5 votes |
public AdditionExtractor(Element additionElement, Class<? extends Annotation> additionAnnotation, Element element, Types types, Elements elements, Errors errors) { super(element, types, elements, errors); this.additionAnnotation = additionAnnotation; try { this.additionElement = MoreElements.asType(additionElement); } catch (Exception e) { errors.addInvalid(additionElement, "%s must be a class", additionElement.getSimpleName()); return; } extract(); }
Example 13
Source File: Parameter.java From auto with Apache License 2.0 | 5 votes |
private static boolean isNullable(AnnotationMirror annotation) { TypeElement annotationType = MoreElements.asType(annotation.getAnnotationType().asElement()); return annotationType.getSimpleName().contentEquals("Nullable") || annotationType .getQualifiedName() .toString() // For NullableDecl and NullableType compatibility annotations .startsWith("org.checkerframework.checker.nullness.compatqual.Nullable"); }
Example 14
Source File: AptThatWritesNativeJsFile.java From j2cl with Apache License 2.0 | 5 votes |
@Override public Set<Element> process( SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) { for (Element value : elementsByAnnotation.get(RunApt.class)) { TypeElement typeElement = MoreElements.asType(value); String packageName = MoreElements.getPackage(typeElement).getQualifiedName().toString(); writeNativeJsFile(packageName, typeElement.getSimpleName().toString()); } writeJsFile("com.google.j2cl.transpiler.integration.nativeinjectionapt", "NativeClass"); return ImmutableSet.of(); }
Example 15
Source File: J2clAstProcessor.java From j2cl with Apache License 2.0 | 5 votes |
private VisitableClass extractVisitableClass(final TypeElement typeElement) { ImmutableList<Field> allFieldsNames = ElementFilter.fieldsIn(typeElement.getEnclosedElements()).stream() .filter(hasAnnotation(Visitable.class)) .map( variableElement -> { TypeMirror fieldType = variableElement.asType(); return new Field( variableElement.getSimpleName().toString(), fieldType, hasAnnotation(Nullable.class).apply(variableElement)); }) .collect(toImmutableList()); if (!hasAcceptMethod(typeElement)) { abortWithError( typeElement.getQualifiedName() + " does not implement \"" + " accept(Processor processor)\"", typeElement); } VisitableClass visitableClass = new VisitableClass(); visitableClass.simpleName = typeElement.getSimpleName().toString(); visitableClass.packageName = MoreElements.getPackage(typeElement).getQualifiedName().toString(); visitableClass.fields = allFieldsNames; visitableClass.isContext = isAnnotationPresent(typeElement, Context.class); if (getSingleVisitableSuper(typeElement) != null) { visitableClass.superclassName = MoreTypes.asElement(getSingleVisitableSuper(typeElement)).getSimpleName().toString(); } TypeElement topElement = typeElement; TypeMirror visitableSuper; while ((visitableSuper = getSingleVisitableSuper(topElement)) != null) { topElement = MoreElements.asType(MoreTypes.asElement(visitableSuper)); } visitableClass.topClassName = topElement.getSimpleName().toString(); return visitableClass; }
Example 16
Source File: ModuleValidator.java From dagger2-sample with Apache License 2.0 | 4 votes |
private void validateProvidesOverrides(TypeElement subject, ValidationReport.Builder<TypeElement> builder, ListMultimap<String, ExecutableElement> allMethodsByName, ListMultimap<String, ExecutableElement> bindingMethodsByName) { // For every @Provides method, confirm it overrides nothing *and* nothing overrides it. // Consider the following hierarchy: // class Parent { // @Provides Foo a() {} // @Provides Foo b() {} // Foo c() {} // } // class Child extends Parent { // @Provides Foo a() {} // Foo b() {} // @Provides Foo c() {} // } // In each of those cases, we want to fail. "a" is clear, "b" because Child is overriding // a method marked @Provides in Parent, and "c" because Child is defining an @Provides // method that overrides Parent. TypeElement currentClass = subject; TypeMirror objectType = elements.getTypeElement(Object.class.getCanonicalName()).asType(); // We keep track of methods that failed so we don't spam with multiple failures. Set<ExecutableElement> failedMethods = Sets.newHashSet(); while (!types.isSameType(currentClass.getSuperclass(), objectType)) { currentClass = MoreElements.asType(types.asElement(currentClass.getSuperclass())); List<ExecutableElement> superclassMethods = ElementFilter.methodsIn(currentClass.getEnclosedElements()); for (ExecutableElement superclassMethod : superclassMethods) { String name = superclassMethod.getSimpleName().toString(); // For each method in the superclass, confirm our @Provides methods don't override it for (ExecutableElement providesMethod : bindingMethodsByName.get(name)) { if (!failedMethods.contains(providesMethod) && elements.overrides(providesMethod, superclassMethod, subject)) { failedMethods.add(providesMethod); builder.addItem(String.format(PROVIDES_METHOD_OVERRIDES_ANOTHER, methodClass.getSimpleName(), methodSignatureFormatter.format(superclassMethod)), providesMethod); } } // For each @Provides method in superclass, confirm our methods don't override it. if (isAnnotationPresent(superclassMethod, methodClass)) { for (ExecutableElement method : allMethodsByName.get(name)) { if (!failedMethods.contains(method) && elements.overrides(method, superclassMethod, subject)) { failedMethods.add(method); builder.addItem(String.format(METHOD_OVERRIDES_PROVIDES_METHOD, methodClass.getSimpleName(), methodSignatureFormatter.format(superclassMethod)), method); } } } allMethodsByName.put(superclassMethod.getSimpleName().toString(), superclassMethod); } } }
Example 17
Source File: ProvisionBinding.java From dagger2-sample with Apache License 2.0 | 4 votes |
/** * Returns a ProvisionBinding for the given element. If {@code resolvedType} is present, this * will return a resolved binding, with the key & type resolved to the given type (using * {@link Types#asMemberOf(DeclaredType, Element)}). */ ProvisionBinding forInjectConstructor(ExecutableElement constructorElement, Optional<TypeMirror> resolvedType) { checkNotNull(constructorElement); checkArgument(constructorElement.getKind().equals(CONSTRUCTOR)); checkArgument(isAnnotationPresent(constructorElement, Inject.class)); checkArgument(!getQualifier(constructorElement).isPresent()); ExecutableType cxtorType = MoreTypes.asExecutable(constructorElement.asType()); DeclaredType enclosingCxtorType = MoreTypes.asDeclared(constructorElement.getEnclosingElement().asType()); // If the class this is constructing has some type arguments, resolve everything. if (!enclosingCxtorType.getTypeArguments().isEmpty() && resolvedType.isPresent()) { DeclaredType resolved = MoreTypes.asDeclared(resolvedType.get()); // Validate that we're resolving from the correct type. checkState(types.isSameType(types.erasure(resolved), types.erasure(enclosingCxtorType)), "erased expected type: %s, erased actual type: %s", types.erasure(resolved), types.erasure(enclosingCxtorType)); cxtorType = MoreTypes.asExecutable(types.asMemberOf(resolved, constructorElement)); enclosingCxtorType = resolved; } Key key = keyFactory.forInjectConstructorWithResolvedType(enclosingCxtorType); checkArgument(!key.qualifier().isPresent()); ImmutableSet<DependencyRequest> dependencies = dependencyRequestFactory.forRequiredResolvedVariables(enclosingCxtorType, constructorElement.getParameters(), cxtorType.getParameterTypes()); Optional<DependencyRequest> membersInjectionRequest = membersInjectionRequest(enclosingCxtorType); Optional<AnnotationMirror> scope = getScopeAnnotation(constructorElement.getEnclosingElement()); TypeElement bindingTypeElement = MoreElements.asType(constructorElement.getEnclosingElement()); return new AutoValue_ProvisionBinding( key, constructorElement, dependencies, findBindingPackage(key), hasNonDefaultTypeParameters(bindingTypeElement, key.type(), types), Optional.<DeclaredType>absent(), Optional.<TypeElement>absent(), Kind.INJECTION, Provides.Type.UNIQUE, wrapOptionalInEquivalence(AnnotationMirrors.equivalence(), scope), membersInjectionRequest); }
Example 18
Source File: ProcessingUtil.java From Auto-Dagger2 with MIT License | 4 votes |
public static boolean areTypesEqual(TypeMirror typeMirror1, TypeMirror typeMirror2) { TypeElement typeElement1 = MoreElements.asType(MoreTypes.asElement(typeMirror1)); TypeElement typeElement2 = MoreElements.asType(MoreTypes.asElement(typeMirror2)); return typeElement1.getQualifiedName().equals(typeElement2.getQualifiedName()); }
Example 19
Source File: Environment.java From sqlitemagic with Apache License 2.0 | 4 votes |
public static TypeElement asTypeElement(TypeMirror mirror) { return MoreElements.asType(asElement(mirror)); }
Example 20
Source File: DependencyRequestFormatter.java From dagger2-sample with Apache License 2.0 | 4 votes |
private StringBuilder appendEnclosingTypeAndMemberName(Element member, StringBuilder builder) { TypeElement type = MoreElements.asType(member.getEnclosingElement()); return builder.append(type.getQualifiedName()) .append('.') .append(member.getSimpleName()); }