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

The following examples show how to use javax.lang.model.element.ExecutableElement#getReturnType() . 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: bazel   File: AutoCodecProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void verifyFactoryMethod(TypeElement encodedType, ExecutableElement elt)
    throws SerializationProcessingFailedException {
  boolean success = elt.getModifiers().contains(Modifier.STATIC);
  if (success) {
    Relation equalityTest = findRelationWithGenerics(elt.getReturnType(), encodedType.asType());
    success = equalityTest == Relation.EQUAL_TO || equalityTest == Relation.INSTANCE_OF;
  }
  if (!success) {
    throw new SerializationProcessingFailedException(
        encodedType,
        "%s tags %s as an Instantiator, but it's not a valid factory method %s, %s",
        encodedType,
        elt.getSimpleName(),
        elt.getReturnType(),
        encodedType.asType());
  }
}
 
Example 2
Source Project: j2objc   File: AnnotationRewriter.java    License: Apache License 2.0 6 votes vote down vote up
private void addDefaultAccessors(
    AnnotationTypeDeclaration node, List<AnnotationTypeMemberDeclaration> members) {
  TypeElement type = node.getTypeElement();
  for (AnnotationTypeMemberDeclaration member : members) {
    ExecutableElement memberElement = member.getExecutableElement();
    AnnotationValue defaultValue = memberElement.getDefaultValue();
    if (defaultValue == null || defaultValue.getValue() == null) {
      continue;
    }

    TypeMirror memberType = memberElement.getReturnType();
    String propName = NameTable.getAnnotationPropertyName(memberElement);

    ExecutableElement defaultGetterElement = GeneratedExecutableElement.newMethodWithSelector(
        propName + "Default", memberType, type)
        .addModifiers(Modifier.STATIC);
    MethodDeclaration defaultGetter = new MethodDeclaration(defaultGetterElement);
    defaultGetter.setHasDeclaration(false);
    Block defaultGetterBody = new Block();
    defaultGetter.setBody(defaultGetterBody);
    defaultGetterBody.addStatement(new ReturnStatement(
        translationUtil.createAnnotationValue(memberType, defaultValue)));
    node.addBodyDeclaration(defaultGetter);
  }
}
 
Example 3
Source Project: netbeans   File: JsfForm.java    License: Apache License 2.0 6 votes vote down vote up
/** Check if there is a setter corresponding with the getter */
public static boolean isReadOnly(Types types, ExecutableElement getter) {
    String setterName = "set" + getter.getSimpleName().toString().substring(3); //NOI18N
    TypeMirror propertyType = getter.getReturnType();
    TypeElement enclosingClass = (TypeElement) getter.getEnclosingElement();
    for (ExecutableElement executableElement : ElementFilter.methodsIn(enclosingClass.getEnclosedElements())) {
        if (executableElement.getSimpleName().contentEquals(setterName)) {
            if (executableElement.getParameters().size() == 1) {
                VariableElement firstParam = executableElement.getParameters().get(0);
                if (types.isSameType(firstParam.asType(), propertyType)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example 4
Source Project: ngAndroid   File: ElementUtils.java    License: Apache License 2.0 6 votes vote down vote up
public TypeMirror getElementType(TypeElement model, String field){
    TypeMirror typeMirror = null;
    String fieldName = field.toLowerCase();
    for(Element f : model.getEnclosedElements()){
        if(f instanceof ExecutableElement) {
            String fName = f.getSimpleName().toString().toLowerCase();
            ExecutableElement exec = (ExecutableElement) f;
            if (fName.equals("set" + fieldName) && isSetter(f)) {
                TypeMirror setType = exec.getParameters().get(0).asType();
                if (typeMirror != null) {
                    checkMatch(model, field, typeMirror, setType);
                }
                typeMirror = setType;
            } else if (fName.equals("get" + fieldName) && isGetter(f)) {
                TypeMirror getType = exec.getReturnType();
                if (typeMirror != null) {
                    checkMatch(model, field, typeMirror, getType);
                }
                typeMirror = getType;
            }
        }
    }
    return typeMirror;
}
 
Example 5
Source Project: FreeBuilder   File: ModelUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines the return type of {@code method}, if called on an instance of type {@code type}.
 *
 * <p>For instance, in this example, myY.getProperty() returns List&lt;T&gt;, not T:<pre><code>
 *    interface X&lt;T&gt; {
 *      T getProperty();
 *    }
 *    &#64;FreeBuilder interface Y&lt;T&gt; extends X&lt;List&lt;T&gt;&gt; { }</code></pre>
 *
 * <p>(Unfortunately, a bug in Eclipse prevents us handling these cases correctly at the moment.
 * javac works fine.)
 */
public static TypeMirror getReturnType(TypeElement type, ExecutableElement method, Types types) {
  try {
    ExecutableType executableType = (ExecutableType)
        types.asMemberOf((DeclaredType) type.asType(), method);
    return executableType.getReturnType();
  } catch (IllegalArgumentException e) {
    // Eclipse incorrectly throws an IllegalArgumentException here:
    //    "element is not valid for the containing declared type"
    // As a workaround for the common case, fall back to the declared return type.
    return method.getReturnType();
  }
}
 
Example 6
Source Project: jackdaw   File: MethodInfo.java    License: Apache License 2.0 5 votes vote down vote up
public static MethodInfo create(final ExecutableElement element) {
    return new MethodInfo(
        TypeUtils.getName(element),
        element.getReturnType(),
        TypeUtils.asTypes(element.getParameters()),
        element
    );
}
 
Example 7
Source Project: immutables   File: Mirrors.java    License: Apache License 2.0 5 votes vote down vote up
AttributeModel(ExecutableElement element) {
  this.element = element;
  this.name = element.getSimpleName().toString();

  TypeMirror type = element.getReturnType();

  this.isArray = type.getKind() == TypeKind.ARRAY;
  this.type = this.isArray ? ((ArrayType) type).getComponentType() : type;
  this.kind = AttributeTypeKind.from(this.type);

  this.suffix = this.isArray ? "[]" : "";
  this.mirrorModel = getMirrorModelIfAnnotation();
}
 
Example 8
Source Project: requery   File: EntityType.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isMethodProcessable(ExecutableElement element) {
    // if an immutable type with an implementation provided skip it
    if (!isUnimplementable() && element().getKind().isClass() && isImmutable() &&
        !element.getModifiers().contains(Modifier.ABSTRACT)) {
        if (!ImmutableAnnotationKind.of(element()).isPresent() ||
            !ImmutableAnnotationKind.of(element()).get().hasAnyMemberAnnotation(element)) {
            return false;
        }
    }
    String name = element.getSimpleName().toString();
    // skip kotlin data class methods with component1, component2.. names
    if (isUnimplementable() &&
        name.startsWith("component") && name.length() > "component".length()) {
        return false;
    }

    TypeMirror type = element.getReturnType();
    boolean isInterface = element().getKind().isInterface();
    boolean isTransient = Mirrors.findAnnotationMirror(element, Transient.class).isPresent();

    // must be a getter style method with no args, can't return void or itself or its builder
    return type.getKind() != TypeKind.VOID &&
           element.getParameters().isEmpty() &&
           (isImmutable() || isInterface || !element.getModifiers().contains(Modifier.FINAL)) &&
           (!isImmutable() || !type.equals(element().asType())) &&
           !type.equals(builderType().orElse(null)) &&
           !element.getModifiers().contains(Modifier.STATIC) &&
           !element.getModifiers().contains(Modifier.DEFAULT) &&
           (!isTransient || isInterface) &&
           !name.equals("toString") && !name.equals("hashCode");
}
 
Example 9
Source Project: pocketknife   File: BuilderProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private FragmentMethodBinding getFragmentMethodBinding(ExecutableElement element) throws InvalidTypeException {
    FragmentMethodBinding binding = new FragmentMethodBinding(element.getSimpleName().toString(), element.getReturnType());
    for (Element parameter : element.getParameters()) {
        binding.addField(getBundleFieldBinding(parameter));
    }
    return binding;
}
 
Example 10
Source Project: bazel   File: AutoCodecProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private ExecutableElement findSetterGivenGetter(ExecutableElement getter, TypeElement builderType)
    throws SerializationProcessingFailedException {
  List<ExecutableElement> methods =
      ElementFilter.methodsIn(env.getElementUtils().getAllMembers(builderType));
  String varName = getNameFromGetter(getter);
  TypeMirror type = getter.getReturnType();
  ImmutableSet<String> setterNames = ImmutableSet.of(varName, addCamelCasePrefix(varName, "set"));

  ExecutableElement setterMethod = null;
  for (ExecutableElement method : methods) {
    if (!method.getModifiers().contains(Modifier.STATIC)
        && !method.getModifiers().contains(Modifier.PRIVATE)
        && setterNames.contains(method.getSimpleName().toString())
        && isSameReturnType(method, builderType)
        && method.getParameters().size() == 1
        && env.getTypeUtils()
            .isSubtype(type, Iterables.getOnlyElement(method.getParameters()).asType())) {
      if (setterMethod != null) {
        throw new SerializationProcessingFailedException(
            builderType,
            "Multiple setter methods for %s found in %s: %s and %s",
            getter,
            builderType,
            setterMethod,
            method);
      }
      setterMethod = method;
    }
  }
  if (setterMethod != null) {
    return setterMethod;
  }

  throw new SerializationProcessingFailedException(
      builderType,
      "No setter found corresponding to getter %s, %s",
      getter.getSimpleName(),
      type);
}
 
Example 11
Source Project: netbeans   File: FromEntityBase.java    License: Apache License 2.0 5 votes vote down vote up
private String getRelationClassName(CompilationController controller, ExecutableElement executableElement, boolean isFieldAccess) {
    TypeMirror passedReturnType = executableElement.getReturnType();
    if (TypeKind.DECLARED != passedReturnType.getKind() || !(passedReturnType instanceof DeclaredType)) {
        return null;
    }
    Types types = controller.getTypes();
    TypeMirror passedReturnTypeStripped = JpaControllerUtil.stripCollection((DeclaredType)passedReturnType, types);
    if (passedReturnTypeStripped == null) {
        return null;
    }
    TypeElement passedReturnTypeStrippedElement = (TypeElement) types.asElement(passedReturnTypeStripped);
    return passedReturnTypeStrippedElement.getSimpleName().toString();
}
 
Example 12
protected boolean isLegalMethod(ExecutableElement method, TypeElement typeElement) {
    WebMethod webMethod = method.getAnnotation(WebMethod.class);
    //SEI cannot have methods with @WebMethod(exclude=true)
    if (typeElement.getKind().equals(ElementKind.INTERFACE) && webMethod != null && webMethod.exclude())
        builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_SEI_ANNOTATION_ELEMENT_EXCLUDE("exclude=true", typeElement.getQualifiedName(), method.toString()), method);
    // With https://jax-ws.dev.java.net/issues/show_bug.cgi?id=577, hasWebMethods has no effect
    if (hasWebMethods && webMethod == null) // backwards compatibility (for legacyWebMethod computation)
        return true;

    if ((webMethod != null) && webMethod.exclude()) {
        return true;
    }
    /*
    This check is not needed as Impl class is already checked that it is not abstract.
    if (typeElement instanceof TypeElement && method.getModifiers().contains(Modifier.ABSTRACT)) {  // use Kind.equals instead of instanceOf
        builder.processError(method.getPosition(), WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_METHOD_IS_ABSTRACT(typeElement.getQualifiedName(), method.getSimpleName()));
        return false;
    }
    */
    TypeMirror returnType = method.getReturnType();
    if (!isLegalType(returnType)) {
        builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_RETURN_TYPE_CANNOT_IMPLEMENT_REMOTE(typeElement.getQualifiedName(),
                method.getSimpleName(),
                returnType), method);
    }
    boolean isOneWay = method.getAnnotation(Oneway.class) != null;
    if (isOneWay && !isValidOneWayMethod(method, typeElement))
        return false;

    SOAPBinding soapBinding = method.getAnnotation(SOAPBinding.class);
    if (soapBinding != null) {
        if (soapBinding.style().equals(SOAPBinding.Style.RPC)) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_RPC_SOAPBINDING_NOT_ALLOWED_ON_METHOD(typeElement.getQualifiedName(), method.toString()), method);
        }
    }

    int paramIndex = 0;
    for (VariableElement parameter : method.getParameters()) {
        if (!isLegalParameter(parameter, method, typeElement, paramIndex++))
            return false;
    }

    if (!isDocLitWrapped() && soapStyle.equals(SOAPStyle.DOCUMENT)) {
        VariableElement outParam = getOutParameter(method);
        int inParams = getModeParameterCount(method, WebParam.Mode.IN);
        int outParams = getModeParameterCount(method, WebParam.Mode.OUT);
        if (inParams != 1) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_AND_NO_ONE_IN(typeElement.getQualifiedName(), method.toString()), method);
        }
        if (returnType.accept(NO_TYPE_VISITOR, null)) {
            if (outParam == null && !isOneWay) {
                builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_NO_OUT(typeElement.getQualifiedName(), method.toString()), method);
            }
            if (outParams != 1) {
                if (!isOneWay && outParams != 0)
                    builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_NO_RETURN_AND_NO_OUT(typeElement.getQualifiedName(), method.toString()), method);
            }
        } else {
            if (outParams > 0) {
                builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_RETURN_AND_OUT(typeElement.getQualifiedName(), method.toString()), outParam);
            }
        }
    }
    return true;
}
 
Example 13
protected boolean isLegalMethod(ExecutableElement method, TypeElement typeElement) {
    WebMethod webMethod = method.getAnnotation(WebMethod.class);
    //SEI cannot have methods with @WebMethod(exclude=true)
    if (typeElement.getKind().equals(ElementKind.INTERFACE) && webMethod != null && webMethod.exclude())
        builder.processError(WebserviceapMessages.WEBSERVICEAP_INVALID_SEI_ANNOTATION_ELEMENT_EXCLUDE("exclude=true", typeElement.getQualifiedName(), method.toString()), method);
    // With https://jax-ws.dev.java.net/issues/show_bug.cgi?id=577, hasWebMethods has no effect
    if (hasWebMethods && webMethod == null) // backwards compatibility (for legacyWebMethod computation)
        return true;

    if ((webMethod != null) && webMethod.exclude()) {
        return true;
    }
    /*
    This check is not needed as Impl class is already checked that it is not abstract.
    if (typeElement instanceof TypeElement && method.getModifiers().contains(Modifier.ABSTRACT)) {  // use Kind.equals instead of instanceOf
        builder.processError(method.getPosition(), WebserviceapMessages.WEBSERVICEAP_WEBSERVICE_METHOD_IS_ABSTRACT(typeElement.getQualifiedName(), method.getSimpleName()));
        return false;
    }
    */
    TypeMirror returnType = method.getReturnType();
    if (!isLegalType(returnType)) {
        builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_RETURN_TYPE_CANNOT_IMPLEMENT_REMOTE(typeElement.getQualifiedName(),
                method.getSimpleName(),
                returnType), method);
    }
    boolean isOneWay = method.getAnnotation(Oneway.class) != null;
    if (isOneWay && !isValidOneWayMethod(method, typeElement))
        return false;

    SOAPBinding soapBinding = method.getAnnotation(SOAPBinding.class);
    if (soapBinding != null) {
        if (soapBinding.style().equals(SOAPBinding.Style.RPC)) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_RPC_SOAPBINDING_NOT_ALLOWED_ON_METHOD(typeElement.getQualifiedName(), method.toString()), method);
        }
    }

    int paramIndex = 0;
    for (VariableElement parameter : method.getParameters()) {
        if (!isLegalParameter(parameter, method, typeElement, paramIndex++))
            return false;
    }

    if (!isDocLitWrapped() && soapStyle.equals(SOAPStyle.DOCUMENT)) {
        VariableElement outParam = getOutParameter(method);
        int inParams = getModeParameterCount(method, WebParam.Mode.IN);
        int outParams = getModeParameterCount(method, WebParam.Mode.OUT);
        if (inParams != 1) {
            builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_AND_NO_ONE_IN(typeElement.getQualifiedName(), method.toString()), method);
        }
        if (returnType.accept(NO_TYPE_VISITOR, null)) {
            if (outParam == null && !isOneWay) {
                builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_NO_OUT(typeElement.getQualifiedName(), method.toString()), method);
            }
            if (outParams != 1) {
                if (!isOneWay && outParams != 0)
                    builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_NO_RETURN_AND_NO_OUT(typeElement.getQualifiedName(), method.toString()), method);
            }
        } else {
            if (outParams > 0) {
                builder.processError(WebserviceapMessages.WEBSERVICEAP_DOC_BARE_RETURN_AND_OUT(typeElement.getQualifiedName(), method.toString()), outParam);
            }
        }
    }
    return true;
}
 
Example 14
@Override
public ValidationReport<ExecutableElement> validate(ExecutableElement producesMethodElement) {
  ValidationReport.Builder<ExecutableElement> builder =
      ValidationReport.Builder.about(producesMethodElement);

  Produces producesAnnotation = producesMethodElement.getAnnotation(Produces.class);
  checkArgument(producesAnnotation != null);

  Element enclosingElement = producesMethodElement.getEnclosingElement();
  if (!isAnnotationPresent(enclosingElement, ProducerModule.class)) {
    builder.addItem(formatModuleErrorMessage(BINDING_METHOD_NOT_IN_MODULE),
        producesMethodElement);
  }

  if (!producesMethodElement.getTypeParameters().isEmpty()) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_TYPE_PARAMETER), producesMethodElement);
  }

  Set<Modifier> modifiers = producesMethodElement.getModifiers();
  if (modifiers.contains(PRIVATE)) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_PRIVATE), producesMethodElement);
  }
  if (modifiers.contains(STATIC)) {
    // TODO(gak): why not?
    builder.addItem(formatErrorMessage(BINDING_METHOD_STATIC), producesMethodElement);
  }
  if (modifiers.contains(ABSTRACT)) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_ABSTRACT), producesMethodElement);
  }

  TypeMirror returnType = producesMethodElement.getReturnType();
  TypeKind returnTypeKind = returnType.getKind();
  if (returnTypeKind.equals(VOID)) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_MUST_RETURN_A_VALUE),
        producesMethodElement);
  }

  // check mapkey is right
  if (!producesAnnotation.type().equals(Produces.Type.MAP)
      && (getMapKeys(producesMethodElement) != null
          && !getMapKeys(producesMethodElement).isEmpty())) {
    builder.addItem(formatErrorMessage(BINDING_METHOD_NOT_MAP_HAS_MAP_KEY),
        producesMethodElement);
  }

  ProvidesMethodValidator.validateMethodQualifiers(builder, producesMethodElement);

  switch (producesAnnotation.type()) {
    case UNIQUE: // fall through
    case SET:
      validateSingleReturnType(builder, returnType);
      break;
    case MAP:
      validateSingleReturnType(builder, returnType);
      ImmutableSet<? extends AnnotationMirror> annotationMirrors =
          getMapKeys(producesMethodElement);
      switch (annotationMirrors.size()) {
        case 0:
          builder.addItem(formatErrorMessage(BINDING_METHOD_WITH_NO_MAP_KEY),
              producesMethodElement);
          break;
        case 1:
          break;
        default:
          builder.addItem(formatErrorMessage(BINDING_METHOD_WITH_MULTIPLE_MAP_KEY),
              producesMethodElement);
          break;
      }
      break;
    case SET_VALUES:
      if (returnTypeKind.equals(DECLARED)
          && MoreTypes.isTypeOf(ListenableFuture.class, returnType)) {
        DeclaredType declaredReturnType = MoreTypes.asDeclared(returnType);
        if (!declaredReturnType.getTypeArguments().isEmpty()) {
          validateSetType(builder, Iterables.getOnlyElement(
              declaredReturnType.getTypeArguments()));
        }
      } else {
        validateSetType(builder, returnType);
      }
      break;
    default:
      throw new AssertionError();
  }

  return builder.build();
}
 
Example 15
Source Project: tinkerpop   File: GremlinDslProcessor.java    License: Apache License 2.0 4 votes vote down vote up
private List<? extends TypeMirror> getTypeArguments(final ExecutableElement templateMethod) {
    final DeclaredType returnTypeMirror = (DeclaredType) templateMethod.getReturnType();
    return returnTypeMirror.getTypeArguments();
}
 
Example 16
Source Project: netbeans   File: ELRenameRefactoring.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void addElements(CompilationContext info, ELElement elem, List<Node> matchingNodes, RefactoringElementsBag refactoringElementsBag) {
    FileObject file = elem.getSnapshot().getSource().getFileObject();
    ModificationResult modificationResult = new ModificationResult();
    List<Difference> differences = new ArrayList<>();

    TypeMirror returnType = null;
    TreePathHandle treePathHandle = rename.getRefactoringSource().lookup(TreePathHandle.class);
    if (treePathHandle != null && treePathHandle.getKind() == Tree.Kind.METHOD) {
        ExecutableElement methodElement = (ExecutableElement) treePathHandle.resolveElement(info.info());
        returnType = methodElement.getReturnType();
    }

    for (Node targetNode : matchingNodes) {
        PositionRef[] position = RefactoringUtil.getPostionRefs(elem, targetNode);
        String renameNewName = rename.getNewName();
        if (renameNewName != null) {
            String newName = renameNewName + "()"; //NOI18N
            if (RefactoringUtil.isPropertyAccessor(renameNewName, returnType)) {
                newName = RefactoringUtil.getPropertyName(renameNewName, returnType);
            } else if (targetNode.jjtGetLastToken().image != null
                    && !targetNode.jjtGetLastToken().image.endsWith(")")) {  //NOI18N
                // issue #245540
                newName = renameNewName;
            }

            // issue #246641
            PositionRef[] childPosition = null;
            if (targetNode.jjtGetNumChildren() > 0) {
                Node child = targetNode.jjtGetChild(0);
                if (child instanceof AstMethodArguments) {
                    childPosition = RefactoringUtil.getPostionRefs(elem, child);
                    newName = renameNewName;
                }
            }
            differences.add(new Difference(Difference.Kind.CHANGE,
                    position[0], childPosition != null ? childPosition[0] : position[1], targetNode.getImage(), newName,
                    NbBundle.getMessage(ELRenameRefactoring.class, "LBL_Update", targetNode.getImage())));
        }
    }
    modificationResult.addDifferences(file, differences);

    refactoringElementsBag.registerTransaction(new RefactoringCommit(Collections.singletonList(modificationResult)));
    for (Difference diff : modificationResult.getDifferences(file)) {
        DiffElement diffElem = DiffElement.create(diff, file, modificationResult);
        refactoringElementsBag.add(refactoring, diffElem);
    }

}
 
Example 17
Source Project: netbeans   File: ELTypeUtilities.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Says whether the given method node and the element's method correspond.
 * @param info context
 * @param methodNode EL's method node
 * @param method method element
 * @param includeSetter whether setters method should be considered as correct - <b>not precise, do not call it in refactoring</b>
 * @return {@code true} if the method node correspond with the method element, {@code false} otherwise
 */
public static boolean isSameMethod(CompilationContext info, Node methodNode, ExecutableElement method, boolean includeSetter) {
    String image = getMethodName(methodNode);
    String methodName = method.getSimpleName().toString();
    TypeMirror methodReturnType = method.getReturnType();
    if (image == null) {
        return false;
    }
    int methodParams = method.getParameters().size();
    if (NodeUtil.isMethodCall(methodNode) &&
            (methodName.equals(image) || RefactoringUtil.getPropertyName(methodName, methodReturnType).equals(image))) {
        //now we are in AstDotSuffix or AstBracketSuffix

        //lets check if the parameters are equal
        List<Node> parameters = getMethodParameters(methodNode);
        int methodNodeParams = parameters.size();
        if (method.isVarArgs()) {
            return methodParams == 1 ? true : methodNodeParams >= methodParams;
        }
        return (method.getParameters().size() == methodNodeParams && haveSameParameters(info, methodNode, method))
                || methodNodeParams == 0 && hasActionEventArgument(method);
    }

    if (methodNode instanceof AstDotSuffix) {
        if (methodName.equals(image) || RefactoringUtil.getPropertyName(methodName, methodReturnType).equals(image)) {
            if (methodNode.jjtGetNumChildren() > 0) {
                for (int i = 0; i < method.getParameters().size(); i++) {
                    final VariableElement methodParameter = method.getParameters().get(i);
                    final Node methodNodeParameter = methodNode.jjtGetChild(i);

                    if (!isSameType(info, methodNodeParameter, methodParameter)) {
                        return false;
                    }
                }
            }

            if (image.equals(methodName)) {
                return true;
            }

            return method.isVarArgs()
                    ? method.getParameters().size() == 1
                    : method.getParameters().isEmpty();
        } else if (includeSetter && RefactoringUtil.getPropertyName(methodName, methodReturnType, true).equals(image)) {
            // issue #225849 - we don't have additional information from the Facelet,
            // believe the naming conventions. This is not used for refactoring actions.
            return true;
        }
    }
    return false;
}
 
Example 18
public TypeMirror getReturnType(ExecutableElement m) {
    return m.getReturnType();
}
 
Example 19
Source Project: netbeans   File: ELTypeUtilities.java    License: Apache License 2.0 4 votes vote down vote up
public static TypeMirror getReturnTypeForGenericClass(CompilationContext info, final ExecutableElement method, ELElement elElement, List<Node> rootToNode) {
    Node node = null;
    for (int i = rootToNode.size() - 1; i > 0; i--) {
        node = rootToNode.get(i);
        if (node instanceof AstIdentifier) {
            break;
        }
    }
    if (node != null) {
        Element element = ELTypeUtilities.resolveElement(info, elElement, node);
        if (element == null) {
            return method.getReturnType();
        }

        TypeMirror type = element.asType();
        // interfaces are at the end of the List - first parameter has to be superclass
        TypeMirror directSupertype = info.info().getTypes().directSupertypes(type).get(0);
        if (directSupertype instanceof DeclaredType) {
            DeclaredType declaredType = (DeclaredType) directSupertype;
            // index of involved type argument
            int indexOfTypeArgument = -1;
            // list of all type arguments
            List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();

            // search for the same method in the generic class
            for (Element enclosedElement : declaredType.asElement().getEnclosedElements()) {
                if (method.equals(enclosedElement)) {
                    TypeMirror returnType = ((ExecutableElement) enclosedElement).getReturnType();
                    // get index of type argument which is returned by involved method
                    indexOfTypeArgument = info.info().getElementUtilities().enclosingTypeElement(method).
                            getTypeParameters().indexOf(((TypeVariable) returnType).asElement());
                    break;
                }
            }
            if (indexOfTypeArgument != -1 && indexOfTypeArgument < typeArguments.size()) {
                return typeArguments.get(indexOfTypeArgument);
            }
        }
    }

    return method.getReturnType();
}
 
Example 20
Source Project: netbeans   File: PatternAnalyser.java    License: Apache License 2.0 4 votes vote down vote up
/** Analyses one method for property charcteristics */
Property analyseMethodForProperties( Parameters p, ExecutableElement method ) {
    // Skip static methods as Introspector does.
    
    if( method.getModifiers().contains(STATIC) ) {
        return null;
    }
    
    String name = nameAsString(method);
    VariableElement[] params = method.getParameters().toArray(new VariableElement[0]);
    TypeMirror returnType = method.getReturnType();

    Property pp = null;

    try {
        if ( params.length == 0 ) {
            if (name.startsWith( GET_PREFIX )) {
                // SimpleGetter
                pp = new Property( p.ci, method, null );
            }
            else if ( returnType.getKind() == TypeKind.BOOLEAN && name.startsWith( IS_PREFIX )) {
                // Boolean getter
                pp = new Property( p.ci, method, null );
            }
        }
        else if ( params.length == 1 ) {
            if ( params[0].asType().getKind() == TypeKind.INT) {
                if(name.startsWith( GET_PREFIX )) {
                    pp = new IdxProperty( p.ci, null, null, method, null );
                } else if ( returnType.getKind() == TypeKind.BOOLEAN && name.startsWith( IS_PREFIX )) {
                    pp = new IdxProperty( p.ci, null, null, method, null );
                } else if (returnType.getKind() == TypeKind.VOID && name.startsWith(SET_PREFIX)) {
                    pp = new Property(p.ci, null, method);
                    // PENDING vetoable => constrained
                }
            }
            else if ( returnType.getKind() == TypeKind.VOID && name.startsWith( SET_PREFIX )) {
                pp = new Property( p.ci, null, method );
                // PENDING vetoable => constrained
            }
        }
        else if ( params.length == 2 ) {
            if ( params[0].asType().getKind() == TypeKind.INT && name.startsWith( SET_PREFIX )) {
                pp = new IdxProperty( p.ci, null, null, null, method );
                // PENDING vetoable => constrained
            }
        }
    }
    catch (IntrospectionException ex) {
        // PropertyPattern constructor found some differencies from design patterns.
        LOG.log(Level.INFO, ex.getMessage(), ex);
        pp = null;
    }

    return pp;
}