Java Code Examples for javax.lang.model.element.ElementKind#METHOD

The following examples show how to use javax.lang.model.element.ElementKind#METHOD . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
private void inspectHierarchy( Element productionElement,
        TypeElement implementor, Set<Element> specializeElements ,
        WebBeansModelImplementation model )
{
    List<? extends Element> enclosedElements = implementor.getEnclosedElements();
    for (Element enclosedElement : enclosedElements) {
        if ( enclosedElement.getKind() != ElementKind.METHOD) {
            continue;
        }
        if ( !productionElement.getSimpleName().contentEquals(
                enclosedElement.getSimpleName()))
        {
            continue;
        }
        Set<Element> probableSpecializes = new HashSet<Element>();
        if ( collectSpecializes( productionElement ,
                (ExecutableElement)enclosedElement , model ,
                probableSpecializes , specializeElements))
        {
            // for one method there could be just one override method in considered class
            specializeElements.addAll( probableSpecializes );
            return;
        }
    }
}
 
Example 2
Source Project: fragmentargs   File: AnnotatedFragment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the given element is a valid setter method and add it to the internal setter
 *
 * @param classMember Could be everything except an field
 */
public void checkAndAddSetterMethod(Element classMember) {

  if (classMember.getKind() == ElementKind.METHOD) {
    ExecutableElement methodElement = (ExecutableElement) classMember;
    String methodName = methodElement.getSimpleName().toString();
    if (methodName.startsWith("set")) {
      ExecutableElement existingSetter = setterMethods.get(methodName);
      if (existingSetter != null) {
        // Check for better visibility
        if (ModifierUtils.compareModifierVisibility(methodElement, existingSetter) == -1) {
          // this method has better visibility so use this one
          setterMethods.put(methodName, methodElement);
        }
      } else {
        setterMethods.put(methodName, methodElement);
      }
    }
  }

}
 
Example 3
Source Project: netbeans   File: AnnotationProcessors.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Determines if the class derives from AbstractProcessor.
 * @param checkOverride checks that getSupported* method is overriden
 * @return true if derived and method is NOT overriden
 */
public boolean canOverrideAbstract(boolean checkOverride) {
    if (!info.getTypes().isSubtype(processor.asType(), abstractProcessorType)) {
        return false;
    }
    if (!checkOverride) {
        return true;
    }
    Element e = info.getElementUtilities().getImplementationOf(abstractGetSupported, processor);
    if (e == null) {
        return true;
    }
    if (!Utilities.isValidElement(e) || e.getKind() != ElementKind.METHOD) {
        return false;
    }
    overridenGetSupported = (ExecutableElement)e;
    return e.getEnclosingElement() == abstractProcessor;
}
 
Example 4
Source Project: netbeans   File: ElementJavadoc.java    License: Apache License 2.0 6 votes vote down vote up
private CharSequence getFragment(Element e) {
    StringBuilder sb = new StringBuilder();
    if (!e.getKind().isClass() && !e.getKind().isInterface()) {
        if (e.getKind() == ElementKind.CONSTRUCTOR) {
            sb.append(e.getEnclosingElement().getSimpleName());
        } else {
            sb.append(e.getSimpleName());
        }
        if (e.getKind() == ElementKind.METHOD || e.getKind() == ElementKind.CONSTRUCTOR) {
            ExecutableElement ee = (ExecutableElement)e;
            sb.append('('); //NOI18N
            for (Iterator<? extends VariableElement> it = ee.getParameters().iterator(); it.hasNext();) {
                VariableElement param = it.next();
                appendType(sb, param.asType(), ee.isVarArgs() && !it.hasNext());
                if (it.hasNext())
                    sb.append(", ");
            }
            sb.append(')'); //NOI18N
        }
    }
    return sb;
}
 
Example 5
Source Project: netbeans   File: AnnotationProcessors.java    License: Apache License 2.0 6 votes vote down vote up
public boolean canOverrideProcessor(boolean checkOverride) {
    if (!info.getTypes().isSubtype(processor.asType(), baseProcessorType)) {
        return false;
    }
    if (!checkOverride) {
        return true;
    }
    ExecutableElement ee = findGetSupported(baseProcessor);
    if (ee == null) {
        return false;
    }
    Element e = info.getElementUtilities().getImplementationOf(ee, processor);
    if (e == null) {
        return true;
    }
    if (!Utilities.isValidElement(e) || e.getKind() != ElementKind.METHOD) {
        return false;
    }
    overridenGetSupported = (ExecutableElement)e;
    return e.getEnclosingElement() == baseProcessor || 
        e.getEnclosingElement() == abstractProcessor;
}
 
Example 6
Source Project: Auto-Dagger2   File: AdditionExtractor.java    License: MIT License 6 votes vote down vote up
@Override
public void extract() {
    targetTypeMirrors = getTypeMirrors("value");
    if (targetTypeMirrors.isEmpty()) {
        // if there's no value, the target is the element itself
        targetTypeMirrors.add(additionElement.asType());
    }

    parameterizedTypeMirrors = getTypeMirrors("parameterizedTypes");

    // @AutoExpose on provider method can have qualifier
    if (additionAnnotation.equals(AutoExpose.class) && element.getKind() == ElementKind.METHOD) {
        qualifierAnnotationMirror = findQualifier(element);
        providerMethodName = element.getSimpleName().toString();
    }
}
 
Example 7
Source Project: netbeans   File: AbstractTestGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 */
private boolean isTestableMethod(ExecutableElement method) {
    if (method.getKind() != ElementKind.METHOD) {
        throw new IllegalArgumentException();
    }

    return setup.isMethodTestable(method);
}
 
Example 8
Source Project: netbeans   File: IsOverriddenVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitMethod(MethodTree tree, Tree d) {
    if (currentClass != null) {
        Element el = info.getTrees().getElement(getCurrentPath());
        
        if (el != null && el.getKind()  == ElementKind.METHOD) {
            if (!el.getModifiers().contains(Modifier.PRIVATE) && !el.getModifiers().contains(Modifier.STATIC)) {
                ExecutableElement overridee = (ExecutableElement) el;
                List<ElementHandle<ExecutableElement>> methods = type2Declaration.get(currentClass);
                
                if (methods == null) {
                    type2Declaration.put(currentClass, methods = new ArrayList<ElementHandle<ExecutableElement>>());
                }

                try {
                    ElementHandle<ExecutableElement> methodHandle = ElementHandle.create(overridee);
                    methods.add(methodHandle);
                    declaration2Tree.put(methodHandle, tree);
                } catch (IllegalArgumentException iae) {
                    LOG.log(
                        Level.INFO,
                        "Unresolvable method: {0}, reason: {1}",    //NOI18N
                        new Object[]{
                            overridee,
                            iae.getMessage()
                        });
                }
            }
        }
    }
    
    super.visitMethod(tree, tree);
    return null;
}
 
Example 9
public static GeneratedExecutableElement newMappedMethod(
    String selector, ExecutableElement method) {
  TypeMirror returnType = ElementUtil.isConstructor(method)
      ? ElementUtil.getDeclaringClass(method).asType() : method.getReturnType();
  return new GeneratedExecutableElement(
      selector, selector, ElementKind.METHOD, returnType, method.getEnclosingElement(),
      method.isVarArgs(), ElementUtil.isSynthetic(method));
}
 
Example 10
Source Project: netbeans   File: ElementUtilities.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Find the element of the method descriptor associated to the functional interface.
 * 
 * @param origin functional interface element
 * @return associated method descriptor element or <code>null</code> if the <code>origin</code> is not a functional interface.
 * @since 2.14
 */
public ExecutableElement getDescriptorElement(TypeElement origin) {
    com.sun.tools.javac.code.Types types = com.sun.tools.javac.code.Types.instance(info.impl.getJavacTask().getContext());
    if (types.isFunctionalInterface((TypeSymbol)origin)) {
        Symbol sym = types.findDescriptorSymbol((TypeSymbol)origin);
        if (sym != null && sym.getKind() == ElementKind.METHOD) {
            return (ExecutableElement)sym;
        }
    }
    return null;
}
 
Example 11
private static void checkElement(Element element) throws ReactPropertyException {
  if (element.getKind() == ElementKind.METHOD
      && element.getModifiers().contains(PUBLIC)) {
    return;
  }

  throw new ReactPropertyException(
      "@ReactProp and @ReachPropGroup annotation must be on a public method",
      element);
}
 
Example 12
Source Project: j2objc   File: ClassFileConverter.java    License: Apache License 2.0 5 votes vote down vote up
private TreeNode convertAnnotationTypeDeclaration(TypeElement element) {
  AnnotationTypeDeclaration annotTypeDecl = new AnnotationTypeDeclaration(element);
  convertBodyDeclaration(annotTypeDecl, element);
  for (Element elem : element.getEnclosedElements()) {
    BodyDeclaration bodyDecl = elem.getKind() == ElementKind.METHOD
        ? convertAnnotationTypeMemberDeclaration((ExecutableElement) elem)
        : (BodyDeclaration) convert(elem, annotTypeDecl);
    if (bodyDecl != null) {
      annotTypeDecl.addBodyDeclaration(bodyDecl);
    }
  }
  removeInterfaceModifiers(annotTypeDecl);
  return annotTypeDecl;
}
 
Example 13
Source Project: vertx-docgen   File: Helper.java    License: Apache License 2.0 5 votes vote down vote up
boolean matchesMethod(Element elt, String memberName, Predicate<ExecutableElement> parametersMatcher) {
  if (elt.getKind() == ElementKind.METHOD) {
    ExecutableElement methodElt = (ExecutableElement) elt;
    return methodElt.getSimpleName().toString().equals(memberName) && parametersMatcher.test(methodElt);
  }
  return false;
}
 
Example 14
Source Project: netbeans   File: CopyFinder.java    License: Apache License 2.0 4 votes vote down vote up
private @NonNull VerifyResult fullVerifyElements(TreePath node, TreePath p) {
    Element nodeEl = info.getTrees().getElement(node);
    Element pEl    = info.getTrees().getElement(p);

    if (nodeEl == null) {
        return pEl == null ? VerifyResult.MATCH : VerifyResult.NO_MATCH_CONTINUE; //TODO: correct? shouldn't be MATCH_CHECK_DEEPER?
    }

    VerifyResult matchingResult;
    
    if (!nodeEl.getModifiers().contains(Modifier.STATIC)) {
        if ((nodeEl.getKind().isClass() || nodeEl.getKind().isInterface())) {
            //class:
            matchingResult = VerifyResult.MATCH;
        } else {
            matchingResult = VerifyResult.MATCH_CHECK_DEEPER;
        }
    } else {
        matchingResult = VerifyResult.MATCH;
        // defect #241261; if the current pattern is a member-select and the selector is a variable, it cannot match
        // a static member of node:
        if (p.getLeaf().getKind() == Tree.Kind.MEMBER_SELECT && node.getLeaf().getKind() == Tree.Kind.MEMBER_SELECT) {
            Tree selector = ((MemberSelectTree)p.getLeaf()).getExpression();
            if (getWildcardTreeName(selector) != null) {
                // className.this/super refer to an instance and can be matched to a variable. They resolve to a variable Element, so exclude them
                Element nodeSelector = info.getTrees().getElement(new TreePath(node, ((MemberSelectTree)node.getLeaf()).getExpression()));
                if (nodeSelector != null && (nodeSelector.getKind().isClass() || nodeSelector.getKind().isInterface())) {
                    matchingResult = VerifyResult.NO_MATCH;
                }  else {
                    matchingResult = VerifyResult.MATCH_CHECK_DEEPER;
                }
            }
        }
    }

    if (nodeEl == pEl) {
        return matchingResult;
    }

    if (nodeEl == null || pEl == null)
        return VerifyResult.NO_MATCH;

    if (nodeEl.getKind() == pEl.getKind() && nodeEl.getKind() == ElementKind.FIELD
            && CLASS.contentEquals(((VariableElement)nodeEl).getSimpleName())
            && CLASS.contentEquals(((VariableElement)pEl).getSimpleName())) {
        return VerifyResult.MATCH_CHECK_DEEPER;
    }

    if (nodeEl.getKind() == pEl.getKind() && nodeEl.getKind() == ElementKind.METHOD) {
        if (info.getElements().overrides((ExecutableElement) nodeEl, (ExecutableElement) pEl, (TypeElement) nodeEl.getEnclosingElement())) {
            return VerifyResult.MATCH_CHECK_DEEPER;
        }
    }

    if (nodeEl.equals(pEl)) {
        return matchingResult;
    }

    if (allowVariablesRemap && nodeEl.equals(bindState.variablesRemapToElement.get(pEl))) {
        return matchingResult;
    }

    TypeMirror nodeTM = info.getTrees().getTypeMirror(node);

    if (nodeTM == null || nodeTM.getKind() == TypeKind.ERROR) {
        return VerifyResult.NO_MATCH_CONTINUE;
    }

    TypeMirror pTM = info.getTrees().getTypeMirror(p);

    if (pTM == null || pTM.getKind() == TypeKind.ERROR) {
        return VerifyResult.NO_MATCH_CONTINUE;
    }

    return VerifyResult.NO_MATCH;
}
 
Example 15
Source Project: litho   File: PropDefaultsExtractor.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * This attempts to extract a prop-default from a <em>method</em>. This is only necessary for
 * Kotlin KAPT generated code, which currently does a rather strange thing where it generates a
 * method <code>void field_name$annotations()</code> for every <code>field_name</code> that has
 * all annotations for said field.
 *
 * <p>So, if we find a method that looks like this, and it contains a <code>PropDefault</code>
 * annotation, we will try to find a matching field of this name and add use it as basis for our
 * prop-default.
 */
private static ImmutableList<PropDefaultModel> extractFromMethod(Element enclosedElement) {
  if (enclosedElement.getKind() != ElementKind.METHOD) {
    return ImmutableList.of();
  }

  final ExecutableElement methodElement = (ExecutableElement) enclosedElement;

  final Annotation propDefaultAnnotation = methodElement.getAnnotation(PropDefault.class);
  if (propDefaultAnnotation == null) {
    return ImmutableList.of();
  }

  final String methodName = methodElement.getSimpleName().toString();

  boolean isPropDefaultWithoutGet =
      methodName.endsWith("$annotations")
          && methodElement.getReturnType().getKind() == TypeKind.VOID;

  final String baseName;

  /*
   * In case an [@PropDefault] annotated variable does not include `get` on the Kotlin
   * annotation, we fallback to the previous method of identifying `PropDefault` values.
   * Note here that this method is deprecated and might be removed from KAPT some time in
   * future.
   *
   * If a user annotates that variable with `@get:PropDefault` we identify the
   * `PropDefault` values through the accompanying `get` method of that variable.
   * */
  if (isPropDefaultWithoutGet) {
    baseName = methodName.subSequence(0, methodName.indexOf('$')).toString();
  } else {
    baseName =
        methodName.replaceFirst("get", "").substring(0, 1).toLowerCase()
            + methodName.replaceFirst("get", "").substring(1);
  }

  final Optional<? extends Element> element =
      enclosedElement.getEnclosingElement().getEnclosedElements().stream()
          .filter(e -> e.getSimpleName().toString().equals(baseName))
          .findFirst();

  final ResType propDefaultResType = ((PropDefault) propDefaultAnnotation).resType();
  final int propDefaultResId = ((PropDefault) propDefaultAnnotation).resId();

  return element
      .map(
          e ->
              ImmutableList.of(
                  new PropDefaultModel(
                      TypeName.get(e.asType()),
                      baseName,
                      ImmutableList.copyOf(new ArrayList<>(methodElement.getModifiers())),
                      methodElement,
                      propDefaultResType,
                      propDefaultResId)))
      .orElseGet(ImmutableList::of);
}
 
Example 16
Source Project: litho   File: EventMethodExtractor.java    License: Apache License 2.0 4 votes vote down vote up
/** Get the delegate methods from the given {@link TypeElement}. */
public static ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>>
    getOnEventMethods(
        Elements elements,
        TypeElement typeElement,
        List<Class<? extends Annotation>> permittedInterStageInputAnnotations,
        Messager messager,
        EnumSet<RunMode> runMode) {
  final List<SpecMethodModel<EventMethod, EventDeclarationModel>> delegateMethods =
      new ArrayList<>();

  for (Element enclosedElement : typeElement.getEnclosedElements()) {
    if (enclosedElement.getKind() != ElementKind.METHOD) {
      continue;
    }

    final OnEvent onEventAnnotation = enclosedElement.getAnnotation(OnEvent.class);
    if (onEventAnnotation != null) {
      final ExecutableElement executableElement = (ExecutableElement) enclosedElement;

      final List<MethodParamModel> methodParams =
          getMethodParams(
              executableElement,
              messager,
              getPermittedMethodParamAnnotations(permittedInterStageInputAnnotations),
              permittedInterStageInputAnnotations,
              ImmutableList.<Class<? extends Annotation>>of());

      final DeclaredType eventClassDeclaredType =
          ProcessorUtils.getAnnotationParameter(
              elements, executableElement, OnEvent.class, "value", DeclaredType.class);
      final Element eventClass = eventClassDeclaredType.asElement();

      // In full mode, we get the return type from the Event class so that we can verify that it
      // matches the return type of the method. In ABI mode, we can't access the Event class so
      // we just use the method return type and leave validation for the full build.
      final TypeName returnType =
          runMode.contains(RunMode.ABI)
              ? TypeName.get(executableElement.getReturnType())
              : EventDeclarationsExtractor.getReturnType(elements, eventClass);
      final ImmutableList<FieldModel> fields =
          runMode.contains(RunMode.ABI)
              ? ImmutableList.of()
              : FieldsExtractor.extractFields(eventClass);

      final SpecMethodModel<EventMethod, EventDeclarationModel> eventMethod =
          SpecMethodModel.<EventMethod, EventDeclarationModel>builder()
              .annotations(ImmutableList.of())
              .modifiers(ImmutableList.copyOf(new ArrayList<>(executableElement.getModifiers())))
              .name(executableElement.getSimpleName())
              .returnTypeSpec(generateTypeSpec(executableElement.getReturnType()))
              .typeVariables(ImmutableList.copyOf(getTypeVariables(executableElement)))
              .methodParams(ImmutableList.copyOf(methodParams))
              .representedObject(executableElement)
              .typeModel(
                  new EventDeclarationModel(
                      ClassName.bestGuess(eventClass.toString()), returnType, fields, eventClass))
              .build();
      delegateMethods.add(eventMethod);
    }
  }

  return ImmutableList.copyOf(delegateMethods);
}
 
Example 17
Source Project: openjdk-8   File: Model01.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Member(ElementKind.METHOD)
public void m2();
 
Example 18
Source Project: immutables   File: Encodings.java    License: Apache License 2.0 4 votes vote down vote up
private boolean processClass(TypeElement type) {
  if (BuilderMirror.isPresent(type)) {
    this.typeBuilder = type;

    if (!typeParams.equals(getTypeParameterNames(type))
        || !type.getModifiers().contains(Modifier.STATIC)) {
      reporter.withElement(type)
          .error("@Encoding.Builder class '%s' should be static with"
              + " the same type parameters as encoding type: %s",
              type.getSimpleName(),
              typesReader.parameters);

      return true;
    }

    for (Element member : type.getEnclosedElements()) {
      if ((member.getKind() == ElementKind.FIELD
          || member.getKind() == ElementKind.METHOD)
          && !memberNames.add(memberPath(member))) {
        reporter.withElement(member)
            .error(memberPath(member)
                + ": Duplicate builder member name '%s'."
                + " Encoding has limitation so that any duplicate method names are not supported,"
                + " even when allowed by JLS: methods cannot have overloads here."
                + " @Encoding.Naming annotation could be used so that actually generated methods might have the same name"
                + " if they are not conflicting as per JLS overload rules",
                member.getSimpleName());
        continue;
      }

      if (member.getKind() == ElementKind.FIELD) {
        if (processBuilderField((VariableElement) member))
          continue;
      }

      if (member.getKind() == ElementKind.METHOD) {
        if (processBuilderMethod((ExecutableElement) member))
          continue;
      }

      if (member.getKind() == ElementKind.INSTANCE_INIT) {
        continue;
      }

      if (member.getSimpleName().contentEquals("<init>")) {
        continue;
      }

      reporter.withElement(member)
          .warning("Unrecognized Builder member '%s' will be ignored", member.getSimpleName());
    }
    return true;
  }
  return false;
}
 
Example 19
private Optional<Getter> create(DeclaredType ownerType, ExecutableElement element) {
  if (element.getKind() != ElementKind.METHOD
      || element.getModifiers().contains(Modifier.STATIC)
      || !element.getModifiers().contains(Modifier.PUBLIC)) {
    return Optional.empty();
  }

  ExecutableType method = (ExecutableType) element.asType();
  if (!method.getParameterTypes().isEmpty()) {
    return Optional.empty();
  }

  if (element.getAnnotation(Encodable.Ignore.class) != null) {
    return Optional.empty();
  }
  Optional<String> fieldName = inferName(element);
  if (!fieldName.isPresent()) {
    return Optional.empty();
  }
  TypeMirror returnType = resolveTypeArguments(ownerType, element.getReturnType());
  String getterExpression = element.toString();

  // Fail to compile if Maps with non-string keys are used, if/when we add support for such maps
  // we should delete this.
  TypeMirror map = types.erasure(elements.getTypeElement("java.util.Map").asType());
  if (types.isAssignable(returnType, map)) {
    TypeMirror keyType = ((DeclaredType) returnType).getTypeArguments().get(0);
    if (!types.isSameType(keyType, elements.getTypeElement("java.lang.String").asType())) {
      messager.printMessage(
          Diagnostic.Kind.ERROR,
          "Cannot encode Maps with non-String keys.",
          ((DeclaredType) returnType).asElement());
    }
  }
  if (types.isAssignable(
      returnType, types.erasure(elements.getTypeElement("java.util.Optional").asType()))) {
    returnType = ((DeclaredType) returnType).getTypeArguments().get(0);
    getterExpression = getterExpression + ".orElse(null)";
  }

  Encodable.Field field = element.getAnnotation(Encodable.Field.class);

  return Optional.of(
      Getter.create(
          fieldName.get(), getterExpression, returnType, field != null && field.inline()));
}
 
Example 20
@Member(ElementKind.METHOD)
public void m1();