Java Code Examples for javax.lang.model.element.ExecutableElement#getEnclosingElement()

The following examples show how to use javax.lang.model.element.ExecutableElement#getEnclosingElement() . 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 check out the related API usage on the sidebar.
Example 1
Source Project: buck   File: ElementsExtendedImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public ExecutableElement getImplementation(ExecutableElement baseMethod, TypeElement inType) {
  ExecutableElement result = null;
  for (ExecutableElement candidate : getAllMethods(inType, baseMethod.getSimpleName())) {
    Element enclosingElement = candidate.getEnclosingElement();
    if (enclosingElement != inType && enclosingElement.getKind().isInterface()) {
      continue;
    }

    if (overrides(candidate, baseMethod, inType) || (result == null && candidate == baseMethod)) {
      result = candidate;
    }
  }
  return result;
}
 
Example 2
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  for (Element annotatedElt : roundEnv.getElementsAnnotatedWith(CodeTranslate.class)) {
    ExecutableElement methodElt = (ExecutableElement) annotatedElt;
    TypeElement typeElt = (TypeElement) methodElt.getEnclosingElement();
    if (typeElt.getQualifiedName().toString().equals(fqn) && methodElt.getSimpleName().toString().equals(method)) {
      for (Lang lang : langs) {
        Result result;
        try {
          String translation = translator.translate(methodElt, false, lang, RenderMode.SNIPPET);
          result = new Result.Source(translation);
        } catch (Exception e) {
          result = new Result.Failure(e);
        }
        results.put(lang, result);
      }
    }
  }
  return false;
}
 
Example 3
protected ErrorDescription[] apply(ExecutableElement subject, ProblemContext ctx) {
    AnnotationMirror methodAnn = Utilities.findAnnotation(subject, ANNOTATION_WEBMETHOD);

    Element classEl = subject.getEnclosingElement();
    if (classEl != null) {
        AnnotationMirror serviceAnn = Utilities.findAnnotation(classEl, ANNOTATION_WEBSERVICE);
        if (serviceAnn != null) {
            AnnotationValue val = Utilities.getAnnotationAttrValue
                    (serviceAnn, ANNOTATION_ATTRIBUTE_SEI);
            if (val != null) {
                String label = NbBundle.getMessage(InvalidWebMethodAnnotation.class,
                        "MSG_WebMethod_NotAllowed");
                Fix fix = new RemoveAnnotation(ctx.getFileObject(),
                        subject, methodAnn);
                Tree problemTree = ctx.getCompilationInfo().getTrees().getTree(subject, methodAnn);
                ctx.setElementToAnnotate(problemTree);
                ErrorDescription problem = createProblem(subject, ctx, label, fix);
                ctx.setElementToAnnotate(null);
                return new ErrorDescription[]{problem};
            }
        }
    }
    return null;
}
 
Example 4
private void processInjectAnnotatedMethod(
    ExecutableElement methodElement,
    Map<TypeElement, List<MethodInjectionTarget>> mapTypeElementToMemberInjectorTargetList) {
  TypeElement enclosingElement = (TypeElement) methodElement.getEnclosingElement();

  // Verify common generated code restrictions.
  if (!isValidInjectAnnotatedMethod(methodElement)) {
    return;
  }

  List<MethodInjectionTarget> methodInjectionTargetList =
      mapTypeElementToMemberInjectorTargetList.get(enclosingElement);
  if (methodInjectionTargetList == null) {
    methodInjectionTargetList = new ArrayList<>();
    mapTypeElementToMemberInjectorTargetList.put(enclosingElement, methodInjectionTargetList);
  }

  mapTypeToMostDirectSuperTypeThatNeedsInjection(enclosingElement);
  methodInjectionTargetList.add(createMethodInjectionTarget(methodElement));
}
 
Example 5
Source Project: sqlitemagic   File: TransformerElement.java    License: Apache License 2.0 6 votes vote down vote up
public void addDbValueToObjectMethod(ExecutableElement method) {
  final TypeElement enclosingElement = (TypeElement) method.getEnclosingElement();

  this.dbValueToObjectMethod = method;
  this.deserializedTypeTransformerElement = enclosingElement;
  this.deserializedTypeTransformerClassName = ClassName.get(enclosingElement);

  if (!hasObjectToDb) {
    final VariableElement firstParam = method.getParameters().get(0);
    rawSerializedType = firstParam.asType();
    serializedType = environment.getSupportedSerializedTypeElement(rawSerializedType);
    rawDeserializedType = method.getReturnType();
    deserializedType = environment.getAnyTypeElement(rawDeserializedType);
  }

  hasDbToObject = true;
}
 
Example 6
Source Project: sqlitemagic   File: TransformerElement.java    License: Apache License 2.0 6 votes vote down vote up
public void addObjectToDbValueMethod(ExecutableElement method) {
  final TypeElement enclosingElement = (TypeElement) method.getEnclosingElement();

  this.objectToDbValueMethod = method;
  this.serializedTypeTransformerElement = enclosingElement;
  this.serializedTypeTransformerClassName = ClassName.get(enclosingElement);

  if (!hasDbToObject) {
    final VariableElement firstParam = method.getParameters().get(0);
    rawDeserializedType = firstParam.asType();
    deserializedType = environment.getAnyTypeElement(rawDeserializedType);
    rawSerializedType = method.getReturnType();
    serializedType = environment.getSupportedSerializedTypeElement(rawSerializedType);
  }

  hasObjectToDb = true;
}
 
Example 7
Source Project: auto   File: AutoValueOrOneOfProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void warnAboutPrimitiveArrays(TypeElement autoValueClass, ExecutableElement getter) {
  boolean suppressed = false;
  Optional<AnnotationMirror> maybeAnnotation =
      getAnnotationMirror(getter, "java.lang.SuppressWarnings");
  if (maybeAnnotation.isPresent()) {
    AnnotationValue listValue = getAnnotationValue(maybeAnnotation.get(), "value");
    suppressed = listValue.accept(new ContainsMutableVisitor(), null);
  }
  if (!suppressed) {
    // If the primitive-array property method is defined directly inside the @AutoValue class,
    // then our error message should point directly to it. But if it is inherited, we don't
    // want to try to make the error message point to the inherited definition, since that would
    // be confusing (there is nothing wrong with the definition itself), and won't work if the
    // inherited class is not being recompiled. Instead, in this case we point to the @AutoValue
    // class itself, and we include extra text in the error message that shows the full name of
    // the inherited method.
    boolean sameClass = getter.getEnclosingElement().equals(autoValueClass);
    Element element = sameClass ? getter : autoValueClass;
    String context = sameClass ? "" : (" Method: " + getter.getEnclosingElement() + "." + getter);
    errorReporter.reportWarning(
        element,
        "An @%s property that is a primitive array returns the original array, which can"
            + " therefore be modified by the caller. If this is OK, you can suppress this warning"
            + " with @SuppressWarnings(\"mutable\"). Otherwise, you should replace the property"
            + " with an immutable type, perhaps a simple wrapper around the original array.%s",
        simpleAnnotationName,
        context);
  }
}
 
Example 8
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 9
Source Project: netbeans   File: JpaControllerUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * TODO: actually it's guess setter from setter, need to review if it's a problem of expected
 * @param setter
 * @return 
 */
public static VariableElement guessGetter(ExecutableElement setter) {
    String name = setter.getSimpleName().toString().substring(3);
    String guessGetterName = "set" + name;
    TypeElement typeElement = (TypeElement) setter.getEnclosingElement();
    for (VariableElement variableElement : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) {
        if (variableElement.getSimpleName().contentEquals(guessGetterName)) {
            return variableElement;
        }
    }
    Logger.getLogger(JpaControllerUtil.class.getName()).log(Level.INFO, "Cannot detect setter associated with getter: {0}", guessGetterName);
    return null;
}
 
Example 10
/**
 * {@inheritDoc}
 */
@Override
public void addComments(ExecutableElement property, Content propertyDocTree) {
    TypeElement holder = (TypeElement)property.getEnclosingElement();
    if (!utils.getFullBody(property).isEmpty()) {
        if (holder.equals(typeElement) ||
                (!utils.isPublic(holder) || utils.isLinkable(holder))) {
            writer.addInlineComment(property, propertyDocTree);
        } else {
            Content link =
                    writer.getDocLink(LinkInfoImpl.Kind.PROPERTY_COPY,
                    holder, property,
                    utils.isIncluded(holder)
                            ? holder.getSimpleName() : holder.getQualifiedName(),
                        false);
            Content codeLink = HtmlTree.CODE(link);
            Content descfrmLabel = HtmlTree.SPAN(HtmlStyle.descfrmTypeLabel,
                    utils.isClass(holder)
                            ? contents.descfrmClassLabel
                            : contents.descfrmInterfaceLabel);
            descfrmLabel.addContent(Contents.SPACE);
            descfrmLabel.addContent(codeLink);
            propertyDocTree.addContent(HtmlTree.DIV(HtmlStyle.block, descfrmLabel));
            writer.addInlineComment(property, propertyDocTree);
        }
    }
}
 
Example 11
Source Project: toothpick   File: FactoryProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isValidInjectAnnotatedConstructor(ExecutableElement element) {
  TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

  // Verify modifiers.
  Set<Modifier> modifiers = element.getModifiers();
  if (modifiers.contains(PRIVATE)) {
    error(
        element,
        "@Inject constructors must not be private in class %s.",
        enclosingElement.getQualifiedName());
    return false;
  }

  // Verify parentScope modifiers.
  Set<Modifier> parentModifiers = enclosingElement.getModifiers();
  if (parentModifiers.contains(PRIVATE)) {
    error(
        element,
        "Class %s is private. @Inject constructors are not allowed in private classes.",
        enclosingElement.getQualifiedName());
    return false;
  }

  if (isNonStaticInnerClass(enclosingElement)) {
    return false;
  }

  for (VariableElement paramElement : element.getParameters()) {
    if (!isValidInjectedType(paramElement)) {
      return false;
    }
  }

  return true;
}
 
Example 12
Source Project: syndesis   File: ActionProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Explicitly add properties that elude reflection implicit strategy
 */
@SuppressWarnings({"PMD.CyclomaticComplexity", "PMD.NPathComplexity"})
private void augmentProperties(ObjectNode root, ExecutableElement element) {
    final TypeElement typedElement = (TypeElement) element.getEnclosingElement();

    if (beanAnnotationClass != null && element.getAnnotation(beanAnnotationClass) != null) {
        root.put("kind", "ENDPOINT");
    } else {
        root.put("kind", "BEAN");
        root.put("entrypoint", typedElement.getQualifiedName().toString() + "::" + element.getSimpleName());
    }
}
 
Example 13
private void processUtilityCandidateMethod(ExecutableElement utilityMethodCandidate, TypeElement originalType) {
  Name name = utilityMethodCandidate.getSimpleName();
  List<? extends VariableElement> parameters = utilityMethodCandidate.getParameters();

  TypeElement definingType = (TypeElement) utilityMethodCandidate.getEnclosingElement();
  boolean nonFinal = !utilityMethodCandidate.getModifiers().contains(Modifier.FINAL);
  boolean nonAbstract = !utilityMethodCandidate.getModifiers().contains(Modifier.ABSTRACT);

  if (isJavaLangObjectType(definingType)) {
    // We ignore methods of java.lang.Object
    return;
  }

  if (name.contentEquals(EQUALS_METHOD)
      && parameters.size() == 1
      && isJavaLangObjectType(parameters.get(0).asType())) {

    if (nonAbstract) {
      type.isEqualToDefined = true;
      type.isEqualToFinal = !nonFinal;

      if (!definingType.equals(originalType) && hasNonInheritedAttributes && nonFinal) {
        report(originalType)
            .warning(About.INCOMPAT,
                "Type inherits overriden 'equals' method but have some non-inherited attributes."
                + " Please override 'equals' with abstract method to have it generate. Otherwise override"
                + " with calling super implemtation to use custom implementation");
      }
    }
    return;
  }

  if (name.contentEquals(HASH_CODE_METHOD)
      && parameters.isEmpty()) {
    if (nonAbstract) {
      type.isHashCodeDefined = true;
      type.isHashCodeFinal = !nonFinal;

      // inherited non-abstract implementation
      if (!definingType.equals(originalType) && hasNonInheritedAttributes && nonFinal) {
        report(originalType)
            .warning(About.INCOMPAT,
                "Type inherits non-default 'hashCode' method but have some non-inherited attributes."
                + " Please override 'hashCode' with abstract method to have it generated. Otherwise override"
                + " with calling super implemtation to use custom implementation");
      }
    }
    return;
  }

  if (name.contentEquals(TO_STRING_METHOD)
      && parameters.isEmpty()) {
    if (nonAbstract) {
      type.isToStringDefined = true;

      // inherited non-abstract implementation
      if (!definingType.equals(originalType) && hasNonInheritedAttributes && nonFinal) {
        report(originalType)
            .warning(About.INCOMPAT,
                "Type inherits non-default 'toString' method but have some non-inherited attributes."
                + " Please override 'toString' with abstract method to have generate it. Otherwise override"
                + " with calling super implementation to use custom implementation");
      }
    }
    return;
  }
}
 
Example 14
public TypeElement getDeclaringClassForMethod(ExecutableElement m) {
    return (TypeElement) m.getEnclosingElement();
}
 
Example 15
public TypeElement getDeclaringClassForMethod(ExecutableElement m) {
    return (TypeElement) m.getEnclosingElement();
}
 
Example 16
Source Project: javapoet   File: MethodSpec.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns a new method spec builder that overrides {@code method}.
 *
 * <p>This will copy its visibility modifiers, type parameters, return type, name, parameters, and
 * throws declarations. An {@link Override} annotation will be added.
 *
 * <p>Note that in JavaPoet 1.2 through 1.7 this method retained annotations from the method and
 * parameters of the overridden method. Since JavaPoet 1.8 annotations must be added separately.
 */
public static Builder overriding(ExecutableElement method) {
  checkNotNull(method, "method == null");

  Element enclosingClass = method.getEnclosingElement();
  if (enclosingClass.getModifiers().contains(Modifier.FINAL)) {
    throw new IllegalArgumentException("Cannot override method on final class " + enclosingClass);
  }

  Set<Modifier> modifiers = method.getModifiers();
  if (modifiers.contains(Modifier.PRIVATE)
      || modifiers.contains(Modifier.FINAL)
      || modifiers.contains(Modifier.STATIC)) {
    throw new IllegalArgumentException("cannot override method with modifiers: " + modifiers);
  }

  String methodName = method.getSimpleName().toString();
  MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName);

  methodBuilder.addAnnotation(Override.class);

  modifiers = new LinkedHashSet<>(modifiers);
  modifiers.remove(Modifier.ABSTRACT);
  modifiers.remove(Modifier.DEFAULT);
  methodBuilder.addModifiers(modifiers);

  for (TypeParameterElement typeParameterElement : method.getTypeParameters()) {
    TypeVariable var = (TypeVariable) typeParameterElement.asType();
    methodBuilder.addTypeVariable(TypeVariableName.get(var));
  }

  methodBuilder.returns(TypeName.get(method.getReturnType()));
  methodBuilder.addParameters(ParameterSpec.parametersOf(method));
  methodBuilder.varargs(method.isVarArgs());

  for (TypeMirror thrownType : method.getThrownTypes()) {
    methodBuilder.addException(TypeName.get(thrownType));
  }

  return methodBuilder;
}
 
Example 17
public TypeElement getDeclaringClassForMethod(ExecutableElement m) {
    return (TypeElement) m.getEnclosingElement();
}
 
Example 18
public TypeElement getDeclaringClassForMethod(ExecutableElement m) {
    return (TypeElement) m.getEnclosingElement();
}
 
Example 19
public TypeElement getDeclaringClassForMethod(ExecutableElement m) {
    return (TypeElement) m.getEnclosingElement();
}
 
Example 20
Source Project: buck   File: BridgeMethods.java    License: Apache License 2.0 4 votes vote down vote up
private void findBridgesToType(TypeElement supertype) {
  if (supertype == subclass) {
    return;
  }

  List<ExecutableElement> supertypeMethods =
      new ArrayList<>(ElementFilter.methodsIn(supertype.getEnclosedElements()));
  // For whatever reason, the members field in the compiler is reversed
  Collections.reverse(supertypeMethods);
  for (ExecutableElement supertypeMethod : supertypeMethods) {
    if (supertypeMethod.getModifiers().contains(Modifier.PRIVATE)
        || supertypeMethod.getModifiers().contains(Modifier.STATIC)
        || supertypeMethod.getModifiers().contains(Modifier.FINAL)
        || isHiddenInType(supertypeMethod, subclass)) {
      continue;
    }

    ExecutableElement languageResolvedMethod =
        elements.getImplementation(supertypeMethod, subclass);
    TypeElement vmResolvedMethodOwner =
        elements.getBinaryImplementationOwner(supertypeMethod, subclass);

    if (vmResolvedMethodOwner == null
        || vmResolvedMethodOwner == supertypeMethod.getEnclosingElement()
        || (languageResolvedMethod != null
            && !types.isSubtype(
                types.erasure(vmResolvedMethodOwner.asType()),
                types.erasure(languageResolvedMethod.getEnclosingElement().asType())))) {
      if (languageResolvedMethod != null
          && isBridgeNeeded(supertypeMethod, languageResolvedMethod, subclass)) {
        if (languageResolvedMethod.getEnclosingElement() != vmResolvedMethodOwner) {
          bridgesNeeded.add(new BridgeMethod(languageResolvedMethod, supertypeMethod));
        }
        // There's a comment in the compiler source about there being a design flaw in
        // Reflection
        // that requires bridge methods to be created if a public class inherits a public method
        // from a non-public supertype.
      } else if (languageResolvedMethod == supertypeMethod
          && languageResolvedMethod.getEnclosingElement() != subclass
          && !languageResolvedMethod.getModifiers().contains(Modifier.FINAL)
          && !supertypeMethod.getModifiers().contains(Modifier.ABSTRACT)
          && !supertypeMethod.getModifiers().contains(Modifier.DEFAULT)
          && supertypeMethod.getModifiers().contains(Modifier.PUBLIC)
          && subclass.getModifiers().contains(Modifier.PUBLIC)
          && !languageResolvedMethod
              .getEnclosingElement()
              .getModifiers()
              .contains(Modifier.PUBLIC)) {
        bridgesNeeded.add(new BridgeMethod(supertypeMethod, supertypeMethod));
      }
    }
  }
}