com.google.auto.common.MoreElements Java Examples

The following examples show how to use com.google.auto.common.MoreElements. 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: PropertyBuilderClassifier.java    From auto with Apache License 2.0 6 votes vote down vote up
private Optional<ExecutableElement> addAllPutAll(
    TypeElement barBuilderTypeElement,
    DeclaredType barBuilderDeclaredType,
    TypeMirror barTypeMirror) {
  return MoreElements.getLocalAndInheritedMethods(barBuilderTypeElement, typeUtils, elementUtils)
      .stream()
      .filter(
          method ->
              ADD_ALL_PUT_ALL.contains(method.getSimpleName().toString())
                  && method.getParameters().size() == 1)
      .filter(
          method -> {
            ExecutableType methodMirror =
                MoreTypes.asExecutable(typeUtils.asMemberOf(barBuilderDeclaredType, method));
            return typeUtils.isAssignable(barTypeMirror, methodMirror.getParameterTypes().get(0));
          })
      .findFirst();
}
 
Example #2
Source File: PathProcessing.java    From Mortar-architect with MIT License 6 votes vote down vote up
private ClassName buildClassName() {
    String name = extractor.getElement().getSimpleName().toString();

    // try to remove NavigationScope at the end of the name
    String newName = removeEndingName(removeEndingName(name, "Scope"), "Navigation");
    if (newName == null) {
        errors.addInvalid("Class name " + newName);
    }

    String pkg = MoreElements.getPackage(extractor.getElement()).getQualifiedName().toString();
    if (StringUtils.isBlank(pkg)) {
        errors.addInvalid("Package name " + pkg);
    }
    pkg = pkg + ".path";

    return ClassName.get(pkg, newName + "Path");
}
 
Example #3
Source File: ScopeExtractor.java    From Mortar-architect with MIT License 6 votes vote down vote up
/**
 * Find annotation that is itself annoted with @Scope
 * If there is one, it will be later applied on the generated component
 * Otherwise the component will be unscoped
 * Throw error if more than one scope annotation found
 */
private AnnotationMirror findScope() {
    AnnotationMirror annotationTypeMirror = null;

    for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
        Element annotationElement = annotationMirror.getAnnotationType().asElement();
        if (MoreElements.isAnnotationPresent(annotationElement, Scope.class)) {
            // already found one scope
            if (annotationTypeMirror != null) {
                errors.addInvalid("Several dagger scopes on same element are not allowed");
                continue;
            }

            annotationTypeMirror = annotationMirror;
        }
    }

    return annotationTypeMirror;
}
 
Example #4
Source File: BindingGraphValidator.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
private void reportCycle(DependencyRequest request, Deque<ResolvedRequest> path,
    final ValidationReport.Builder<BindingGraph> reportBuilder) {
  ImmutableList<DependencyRequest> pathElements = ImmutableList.<DependencyRequest>builder()
      .add(request)
      .addAll(Iterables.transform(path, REQUEST_FROM_RESOLVED_REQUEST))
      .build();
  ImmutableList<String> printableDependencyPath = FluentIterable.from(pathElements)
      .transform(dependencyRequestFormatter)
      .filter(Predicates.not(Predicates.equalTo("")))
      .toList()
      .reverse();
  DependencyRequest rootRequest = path.getLast().request();
  TypeElement componentType =
      MoreElements.asType(rootRequest.requestElement().getEnclosingElement());
  // TODO(cgruber): Restructure to provide a hint for the start and end of the cycle.
  reportBuilder.addItem(
      String.format(ErrorMessages.CONTAINS_DEPENDENCY_CYCLE_FORMAT,
          componentType.getQualifiedName(),
          rootRequest.requestElement().getSimpleName(),
          Joiner.on("\n")
              .join(printableDependencyPath.subList(1, printableDependencyPath.size()))),
      rootRequest.requestElement());
}
 
Example #5
Source File: ScopeProcessing.java    From Mortar-architect with MIT License 6 votes vote down vote up
private ClassName buildClassName(Element element) {
    String name = element.getSimpleName().toString();

    // try to remove Presenter at the end of the name
    String newName = removeEndingName(name, "Presenter");
    if (newName == null) {
        errors.addInvalid("Class name " + newName);
    }

    String pkg = MoreElements.getPackage(element).getQualifiedName().toString();
    if (StringUtils.isBlank(pkg)) {
        errors.addInvalid("Package name " + pkg);
    }
    pkg = pkg + ".stackable";

    return ClassName.get(pkg, newName + "Stackable");
}
 
Example #6
Source File: BaseAbstractProcessor.java    From RapidORM with Apache License 2.0 6 votes vote down vote up
/**
 * Get class name of special element
 */
protected String getElementOwnerClassName(Element element) {
    String clazzName;

    // todo: Get the Class which element's owner.
    ElementKind elementKind = element.getKind();
    if (ElementKind.FIELD == elementKind) {
        clazzName = MoreElements.asVariable(element).getEnclosingElement().toString();
        logger("[getDIClazzSafe]MoreElements.asVariable().getEnclosingElement(): " + MoreElements.asVariable(element).getEnclosingElement());
    } else if (ElementKind.METHOD == elementKind) {
        clazzName = MoreElements.asExecutable(element).getEnclosingElement().toString();
    } else {
        clazzName = typeUtils.erasure(element.asType()).toString();
    }


    return clazzName;
}
 
Example #7
Source File: BuilderSpec.java    From RetroFacebook with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: PaperParcelAutoValueExtension.java    From paperparcel with Apache License 2.0 6 votes vote down vote up
private static boolean needsContentDescriptor(Context context) {
  ProcessingEnvironment env = context.processingEnvironment();
  TypeElement autoValueTypeElement = context.autoValueClass();
  Elements elements = env.getElementUtils();
  @SuppressWarnings("deprecation") // Support for kapt2
  ImmutableSet<ExecutableElement> methods =
      MoreElements.getLocalAndInheritedMethods(autoValueTypeElement, elements);
  for (ExecutableElement element : methods) {
    if (element.getSimpleName().contentEquals("describeContents")
        && MoreTypes.isTypeOf(int.class, element.getReturnType())
        && element.getParameters().isEmpty()
        && !element.getModifiers().contains(ABSTRACT)) {
      return false;
    }
  }
  return true;
}
 
Example #9
Source File: ElementUtil.java    From RapidORM with Apache License 2.0 6 votes vote down vote up
/**
 * 两组参数类型相同
 */
public static boolean deepSame(List<? extends VariableElement> _this, List<? extends VariableElement> _that) {
    if (null == _this && null == _that) {
        return true;
    }

    if (null == _this || null == _that) {
        return false;
    }

    if (_this.size() != _that.size()) {
        return false;
    }

    for (int i = 0, len = _this.size(); i < len; i++) {
        VariableElement _thisEle = _this.get(i);
        VariableElement _thatEle = _that.get(i);

        if (!MoreElements.asType(_thisEle).getQualifiedName().toString()
                .equals(MoreElements.asType(_thatEle).getQualifiedName().toString())) {
            return false;
        }
    }

    return true;
}
 
Example #10
Source File: BuilderSpec.java    From RetroFacebook with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: ProductionComponentProcessingStep.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
@Override
public void process(SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) {
  Set<? extends Element> componentElements = elementsByAnnotation.get(ProductionComponent.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.forProductionComponent(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 #12
Source File: Utils.java    From paperparcel with Apache License 2.0 6 votes vote down vote up
private static Optional<AnnotationMirror> findOptionsMirror(TypeElement element) {
  Optional<AnnotationMirror> result =
      MoreElements.getAnnotationMirror(element, PaperParcel.Options.class);
  if (!result.isPresent()) {
    ImmutableSet<? extends AnnotationMirror> annotatedAnnotations =
        AnnotationMirrors.getAnnotatedAnnotations(element, PaperParcel.Options.class);
    if (annotatedAnnotations.size() > 1) {
      throw new IllegalStateException("PaperParcel options applied twice.");
    } else if (annotatedAnnotations.size() == 1) {
      AnnotationMirror annotatedAnnotation = annotatedAnnotations.iterator().next();
      result = MoreElements.getAnnotationMirror(
          annotatedAnnotation.getAnnotationType().asElement(), PaperParcel.Options.class);
    } else {
      TypeMirror superType = element.getSuperclass();
      if (superType.getKind() != TypeKind.NONE) {
        TypeElement superElement = asType(asDeclared(superType).asElement());
        result = findOptionsMirror(superElement);
      }
    }
  }
  return result;
}
 
Example #13
Source File: StringReducerElement.java    From reductor with Apache License 2.0 6 votes vote down vote up
private static List<AutoReducerConstructor> parseConstructors(TypeElement typeElement) throws ValidationException {
    List<AutoReducerConstructor> constructors = new ArrayList<>();
    boolean hasNonDefaultConstructors = false;
    for (Element element : typeElement.getEnclosedElements()) {
        if (element.getKind() == ElementKind.CONSTRUCTOR) {
            ExecutableElement executableElement = MoreElements.asExecutable(element);

            if (executableElement.getModifiers().contains(Modifier.PRIVATE)) continue;

            List<? extends VariableElement> parameters = executableElement.getParameters();

            hasNonDefaultConstructors |= parameters.size() != 0;
            constructors.add(new AutoReducerConstructor(executableElement));
        }
    }

    //if we only have one default constructor, it can be omitted
    if (!hasNonDefaultConstructors && constructors.size() == 1) return Collections.emptyList();

    //this is the case when all constructors are private
    if (constructors.size() == 0)
        throw new ValidationException(typeElement, "No accessible constructors available for class %s", typeElement);

    return constructors;
}
 
Example #14
Source File: ReduceAction.java    From reductor with Apache License 2.0 6 votes vote down vote up
private static void validateActionCreator(ExecutableElement element,
                                          String actionName,
                                          TypeMirror actionCreator,
                                          ArrayList<VariableElement> args,
                                          Map<String, ActionCreatorElement> knownActionCreators,
                                          Env env) throws ValidationException {
    Element actionCreatorElement = MoreTypes.asElement(actionCreator);
    if (!MoreElements.isAnnotationPresent(actionCreatorElement, ActionCreator.class)) {
        throw new ValidationException(element, "Action creator %s should be annotated with @%s", actionCreator, ActionCreator.class.getSimpleName());
    }

    ActionCreatorElement creatorElement = knownActionCreators.get(env.getElements().getBinaryName((TypeElement) actionCreatorElement).toString());
    if (creatorElement == null) {
        throw new ElementNotReadyException();
    }
    if (!creatorElement.hasAction(actionName, args)) {
        throw new ValidationException(element, "Cannot find action creator for action \"%s\" and args %s in interface %s", actionName, toString(args), creatorElement.getName(env));
    }
}
 
Example #15
Source File: BuilderSpec.java    From SimpleWeibo with Apache License 2.0 6 votes vote down vote up
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 #16
Source File: PathExtractor.java    From Mortar-architect with MIT License 6 votes vote down vote up
@Override
public void extract() {
    if (element.getKind() != ElementKind.CLASS) {
        errors.addInvalid("Annotation can be applied only on a class");
        return;
    }

    viewTypeMirror = ExtractorUtils.getValueFromAnnotation(element, AutoPath.class, ANNOTATION_VIEW);
    if (viewTypeMirror == null) {
        errors.addMissing("withView() value");
    }

    constructorElements = new ArrayList<>();
    for (Element e : element.getEnclosedElements()) {
        if (e.getKind() == ElementKind.CONSTRUCTOR) {
            constructorElements.add(MoreElements.asExecutable(e));
        }
    }
}
 
Example #17
Source File: ComponentProcessing.java    From Auto-Dagger2 with MIT License 6 votes vote down vote up
@Override
public boolean processElement(Element element, Errors.ElementErrors elementErrors) {
    if (ElementKind.ANNOTATION_TYPE.equals(element.getKind())) {
        // @AutoComponent is applied on another annotation, find out the targets of that annotation
        Set<? extends Element> targetElements = roundEnvironment.getElementsAnnotatedWith(MoreElements.asType(element));
        for (Element targetElement : targetElements) {
            process(targetElement, element);
            if (errors.hasErrors()) {
                return false;
            }
        }
        return true;
    }

    process(element, element);

    if (errors.hasErrors()) {
        return false;
    }

    return true;
}
 
Example #18
Source File: PaperParcelAutoValueExtensionValidator.java    From paperparcel with Apache License 2.0 6 votes vote down vote up
@Nullable private ExecutableElement findWriteToParcel(TypeElement subject) {
  TypeMirror parcel = elements.getTypeElement("android.os.Parcel").asType();
  @SuppressWarnings("deprecation") // Support for kapt2
  ImmutableSet<ExecutableElement> methods =
      MoreElements.getLocalAndInheritedMethods(subject, elements);
  for (ExecutableElement element : methods) {
    if (element.getSimpleName().contentEquals("writeToParcel")
        && MoreTypes.isTypeOf(void.class, element.getReturnType())
        && !element.getModifiers().contains(Modifier.ABSTRACT)) {
      List<? extends VariableElement> parameters = element.getParameters();
      if (parameters.size() == 2
          && types.isSameType(parcel, parameters.get(0).asType())
          && MoreTypes.isTypeOf(int.class, parameters.get(1).asType())) {
        return element;
      }
    }
  }
  return null;
}
 
Example #19
Source File: ConfigurationAnnotations.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
/** 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 #20
Source File: JUnit3Validator.java    From j2cl with Apache License 2.0 6 votes vote down vote up
public boolean isJUnit3Suite(TypeElement typeElement) {
  return ElementFilter.methodsIn(typeElement.getEnclosedElements())
      .stream()
      .filter(MoreElements.hasModifiers(Sets.newHashSet(Modifier.STATIC, Modifier.PUBLIC)))
      .anyMatch(
          method -> {
            if (!method.getSimpleName().contentEquals("suite")) {
              return false;
            }

            if (!method.getParameters().isEmpty()) {
              return false;
            }

            TypeElement returnElement = MoreApt.asTypeElement(method.getReturnType());
            if (returnElement == null) {
              return false;
            }

            return isTestClass(returnElement) || isJunit3TestCase(returnElement);
          });
}
 
Example #21
Source File: JUnit3TestDataExtractor.java    From j2cl with Apache License 2.0 6 votes vote down vote up
public TestClass extractTestData(TypeElement typeElement) {
  // JUnit3 only has one setUp/tearDown method, but it is protected
  // so we added "hidden" setup and tearDown methods in our version of TestCase
  TestMethod setupMethod =
      TestMethod.builder().isStatic(false).javaMethodName("__hiddenSetUp").build();
  TestMethod tearDownMethod =
      TestMethod.builder().isStatic(false).javaMethodName("__hiddenTearDown").build();

  return TestClass.builder()
      .packageName(MoreElements.getPackage(typeElement).getQualifiedName().toString())
      .simpleName(typeElement.getSimpleName().toString())
      .qualifiedName(typeElement.getQualifiedName().toString())
      .testMethods(getJUnit3TestMethods(MoreApt.getClassHierarchy(typeElement)))
      .beforeMethods(ImmutableList.of(setupMethod))
      .afterMethods(ImmutableList.of(tearDownMethod))
      .beforeClassMethods(ImmutableList.<TestMethod>of())
      .afterClassMethods(ImmutableList.<TestMethod>of())
      .build();
}
 
Example #22
Source File: ComponentProcessingStep.java    From dagger2-sample with Apache License 2.0 6 votes vote down vote up
@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 #23
Source File: TypeSimplifier.java    From auto with Apache License 2.0 5 votes vote down vote up
String simplifiedClassName(DeclaredType type) {
  TypeElement typeElement = MoreElements.asType(type.asElement());
  TypeElement top = topLevelType(typeElement);
  // We always want to write a class name starting from the outermost class. For example,
  // if the type is java.util.Map.Entry then we will import java.util.Map and write Map.Entry.
  String topString = top.getQualifiedName().toString();
  if (imports.containsKey(topString)) {
    String suffix = typeElement.getQualifiedName().toString().substring(topString.length());
    return imports.get(topString).spelling + suffix;
  } else {
    return typeElement.getQualifiedName().toString();
  }
}
 
Example #24
Source File: Optionalish.java    From auto with Apache License 2.0 5 votes vote down vote up
static boolean isOptional(TypeMirror type) {
  if (type.getKind() != TypeKind.DECLARED) {
    return false;
  }
  DeclaredType declaredType = MoreTypes.asDeclared(type);
  TypeElement typeElement = MoreElements.asType(declaredType.asElement());
  return OPTIONAL_CLASS_NAMES.contains(typeElement.getQualifiedName().toString())
      && typeElement.getTypeParameters().size() == declaredType.getTypeArguments().size();
}
 
Example #25
Source File: FactoryDescriptorGenerator.java    From auto with Apache License 2.0 5 votes vote down vote up
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 #26
Source File: Parameter.java    From auto with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: ComponentDescriptor.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
private static void findLocalAndInheritedMethods(Elements elements, TypeElement type,
    List<ExecutableElement> methods) {
  for (TypeMirror superInterface : type.getInterfaces()) {
    findLocalAndInheritedMethods(
        elements, MoreElements.asType(MoreTypes.asElement(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.
    findLocalAndInheritedMethods(
        elements, MoreElements.asType(MoreTypes.asElement(type.getSuperclass())), methods);
  }
  // Add each method of this class, and in so doing remove any inherited method it overrides.
  // This algorithm is quadratic in the number of methods but it's hard to see how to improve
  // that while still using Elements.overrides.
  List<ExecutableElement> theseMethods = ElementFilter.methodsIn(type.getEnclosedElements());
  for (ExecutableElement method : theseMethods) {
    if (!method.getModifiers().contains(Modifier.PRIVATE)) {
      boolean alreadySeen = false;
      for (Iterator<ExecutableElement> methodIter = methods.iterator(); methodIter.hasNext();) {
        ExecutableElement otherMethod = methodIter.next();
        if (elements.overrides(method, otherMethod, type)) {
          methodIter.remove();
        } else if (method.getSimpleName().equals(otherMethod.getSimpleName())
            && method.getParameters().equals(otherMethod.getParameters())) {
          // If we inherit this method on more than one path, we don't want to add it twice.
          alreadySeen = true;
        }
      }
      if (!alreadySeen) {
        methods.add(method);
      }
    }
  }
}
 
Example #28
Source File: ProvisionBinding.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
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 #29
Source File: InjectBindingRegistry.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
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 #30
Source File: AutoValueOrOneOfProcessor.java    From auto with Apache License 2.0 5 votes vote down vote up
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);
}