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

The following examples show how to use javax.lang.model.element.ExecutableElement#isVarArgs() . 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: ThrowableInitCause.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean findConstructor(Element el, Types t, List<TypeMirror> paramTypes) {
    boolean found = false;
    OUTER: for (ExecutableElement ee : ElementFilter.constructorsIn(el.getEnclosedElements())) {
        if (ee.isVarArgs() || ee.getParameters().size() != paramTypes.size()) {
            continue;
        }

        Iterator<? extends VariableElement> p = ee.getParameters().iterator();
        Iterator<TypeMirror> expectedType = paramTypes.iterator();

        while (p.hasNext() && expectedType.hasNext()) {
            if (!t.isAssignable(expectedType.next(), p.next().asType())) {
                continue OUTER;
            }
        }

        found = true;
        break;
    }

    return found;
}
 
Example 2
Source File: EnumRewriter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if an enum doesn't have custom or renamed constructors,
 * vararg constructors or constants with anonymous class extensions.
 */
private boolean isSimpleEnum(EnumDeclaration node) {
  TypeElement type = node.getTypeElement();
  for (EnumConstantDeclaration constant : node.getEnumConstants()) {
    ExecutableElement method = constant.getExecutableElement();
    if (method.getParameters().size() > 0 || method.isVarArgs()) {
      return false;
    }
    if (ElementUtil.hasAnnotation(method, ObjectiveCName.class)) {
      return false;
    }
    TypeElement valueType = ElementUtil.getDeclaringClass(method);
    if (valueType != type) {
      return false;
    }
  }
  return true;
}
 
Example 3
Source File: ELWhereUsedQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean searchPropertyReferences(CompilationContext info, ExecutableElement targetType) {
    // no params method
    if (targetType.getParameters().isEmpty()) {
        return true;
    }

    int argumentsNumber = targetType.getParameters().size();
    if (argumentsNumber != 1) {
        return false;
    }

    // method accepts one vararg parameter
    if (targetType.isVarArgs()) {
        return true;
    }

    // method accepts one argument which can be injected by JSF framework
    VariableElement parameter = targetType.getParameters().get(0);
    if (ELTypeUtilities.isSubtypeOf(info, parameter.asType(), FACES_EVENT_CLASS)) {
        return true;
    }

    return false;
}
 
Example 4
Source File: GeneratedExecutableElement.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public static GeneratedExecutableElement mutableCopy(String selector, ExecutableElement method) {
  GeneratedExecutableElement generatedMethod =
      new GeneratedExecutableElement(
          method.getSimpleName().toString(),
          selector,
          method.getKind(),
          method.getReturnType(),
          method.getEnclosingElement(),
          method.isVarArgs(),
          ElementUtil.isSynthetic(method));
  generatedMethod.addAnnotationMirrors(method.getAnnotationMirrors());
  generatedMethod.addModifiers(method.getModifiers());
  generatedMethod.parameters.addAll(method.getParameters());
  generatedMethod.thrownTypes.addAll(method.getThrownTypes());
  generatedMethod.typeParameters.addAll(method.getTypeParameters());
  return generatedMethod;
}
 
Example 5
Source File: Utils.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public String makeSignature(ExecutableElement e, boolean full, boolean ignoreTypeParameters) {
    StringBuilder result = new StringBuilder();
    result.append("(");
    Iterator<? extends VariableElement> iterator = e.getParameters().iterator();
    while (iterator.hasNext()) {
        VariableElement next = iterator.next();
        TypeMirror type = next.asType();
        result.append(getTypeSignature(type, full, ignoreTypeParameters));
        if (iterator.hasNext()) {
            result.append(", ");
        }
    }
    if (e.isVarArgs()) {
        int len = result.length();
        result.replace(len - 2, len, "...");
    }
    result.append(")");
    return result.toString();
}
 
Example 6
Source File: SourceCodeAnalysisImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private Stream<TypeMirror> parameterType(ExecutableElement method, ExecutableType methodType, int paramIndex, boolean allowVarArgsArray) {
    int paramCount = methodType.getParameterTypes().size();
    if (paramIndex >= paramCount && !method.isVarArgs())
        return Stream.empty();
    if (paramIndex < paramCount - 1 || !method.isVarArgs())
        return Stream.of(methodType.getParameterTypes().get(paramIndex));
    TypeMirror varargType = methodType.getParameterTypes().get(paramCount - 1);
    TypeMirror elemenType = ((ArrayType) varargType).getComponentType();
    if (paramIndex >= paramCount || !allowVarArgsArray)
        return Stream.of(elemenType);
    return Stream.of(varargType, elemenType);
}
 
Example 7
Source File: BuilderSpec.java    From auto with Apache License 2.0 5 votes vote down vote up
private static String parameterTypeString(ExecutableElement setter, TypeMirror parameterType) {
  if (setter.isVarArgs()) {
    TypeMirror componentType = MoreTypes.asArray(parameterType).getComponentType();
    // This is a bit ugly. It's OK to annotate just the component type, because if it is
    // say `@Nullable String` then we will end up with `@Nullable String...`. Unlike the
    // normal array case, we can't have the situation where the array itself is annotated;
    // you can write `String @Nullable []` to mean that, but you can't write
    // `String @Nullable ...`.
    return TypeEncoder.encodeWithAnnotations(componentType) + "...";
  } else {
    return TypeEncoder.encodeWithAnnotations(parameterType);
  }
}
 
Example 8
Source File: AccessFlags.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the method access flags (see JVMS8 4.6) for the given executable element, augmented by the
 * special ASM pseudo-access flag for @Deprecated methods.
 */
public int getAccessFlags(ExecutableElement executableElement) {
  int result = getCommonAccessFlags(executableElement);

  if (executableElement.isVarArgs()) {
    result = result | Opcodes.ACC_VARARGS;
  }

  return result;
}
 
Example 9
Source File: MetadataWriter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the modifiers for a specified method, including internal ones.
 * All method modifiers are defined in the JVM specification, table 4.5.
 */
private static int getMethodModifiers(ExecutableElement method) {
  int modifiers = ElementUtil.fromModifierSet(method.getModifiers());
  if (method.isVarArgs()) {
    modifiers |= ElementUtil.ACC_VARARGS;
  }
  if (ElementUtil.isSynthetic(method)) {
    modifiers |= ElementUtil.ACC_SYNTHETIC;
  }
  return modifiers;
}
 
Example 10
Source File: Autoboxer.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void convertArguments(ExecutableElement method, List<Expression> args) {
  List<? extends VariableElement> params = method.getParameters();
  for (int i = 0; i < args.size(); i++) {
    TypeMirror paramType;
    if (method.isVarArgs() && i >= params.size() - 1) {
      paramType = ((ArrayType) params.get(params.size() - 1).asType()).getComponentType();
    } else {
      paramType = params.get(i).asType();
    }
    boxOrUnboxExpression(args.get(i), paramType);
  }
}
 
Example 11
Source File: GeneratedExecutableElement.java    From j2objc with Apache License 2.0 5 votes vote down vote up
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 12
Source File: MethodEntity.java    From RxPay with Apache License 2.0 5 votes vote down vote up
public MethodEntity(ExecutableElement methodElement, Types typeMirror, Elements elementUtils) {
    this.methodElement = methodElement;
    this.returnType = methodElement.getReturnType().toString();
    this.parameterElements = methodElement.getParameters();
    this.isVarArgs = methodElement.isVarArgs();
    this.methodName = methodElement.getSimpleName().toString();
    this.exceptionTypes = methodElement.getThrownTypes();
    this.typeParameterElements = methodElement.getTypeParameters();
    this.classSimpleName = methodElement.getEnclosingElement().getSimpleName().toString();
    this.classQualifiedName = ((TypeElement) methodElement.getEnclosingElement()).getQualifiedName().toString();
    this.packageName = elementUtils.getPackageOf(methodElement).getQualifiedName().toString();
}
 
Example 13
Source File: ReplaceConstructorWithBuilderUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ReplaceConstructorWithBuilderUI(TreePathHandle constructor, CompilationInfo info) {
    this.refactoring = new ReplaceConstructorWithBuilderRefactoring(constructor);
    ExecutableElement contructorElement = (ExecutableElement) constructor.resolveElement(info);
    this.name = contructorElement.getSimpleName().toString();
    MethodTree constTree = (MethodTree) constructor.resolve(info).getLeaf();
    paramaterNames = new ArrayList<String>();
    parameterTypes = new ArrayList<String>();
    parameterTypeVars = new ArrayList<Boolean>();
    boolean varargs = contructorElement.isVarArgs();
    List<? extends VariableElement> parameterElements = contructorElement.getParameters();
    List<? extends VariableTree> parameters = constTree.getParameters();
    for (int i = 0; i < parameters.size(); i++) {
        VariableTree var = parameters.get(i);
        paramaterNames.add(var.getName().toString());
        String type = contructorElement.getParameters().get(i).asType().toString();
        if(varargs && i+1 == parameters.size()) {
            if(var.getType().getKind() == Tree.Kind.ARRAY_TYPE) {
                ArrayTypeTree att = (ArrayTypeTree) var.getType();
                type = att.getType().toString();
                type += "..."; //NOI18N
            }
        }
        parameterTypes.add(type);
        parameterTypeVars.add(parameterElements.get(i).asType().getKind() == TypeKind.TYPEVAR);
    }
    TypeElement typeEl = (TypeElement) contructorElement.getEnclosingElement();
    if(typeEl.getNestingKind() != NestingKind.TOP_LEVEL) {
        PackageElement packageOf = info.getElements().getPackageOf(typeEl);
        builderFQN = packageOf.toString() + "." + typeEl.getSimpleName().toString();
    } else {
        builderFQN = typeEl.getQualifiedName().toString();
    }
    buildMethodName = "create" + typeEl.getSimpleName();
}
 
Example 14
Source File: ElementNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String createHtmlHeader(boolean deprecated, ExecutableElement e) {
    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    if (deprecated) sb.append("<s>");
    if (e.getKind() == ElementKind.CONSTRUCTOR) {
        sb.append(e.getEnclosingElement().getSimpleName());
    } else {
        sb.append(e.getSimpleName());
    }
    if (deprecated) sb.append("</s>");
    sb.append("("); // NOI18N
    for(Iterator<? extends VariableElement> it = e.getParameters().iterator(); it.hasNext(); ) {
        VariableElement param = it.next();
        if (!it.hasNext() && e.isVarArgs() && param.asType().getKind() == TypeKind.ARRAY) {
            sb.append(translateToHTML(print(((ArrayType) param.asType()).getComponentType())));
            sb.append("...");
        } else {
            sb.append(translateToHTML(print(param.asType())));
        }
        sb.append(" "); // NOI18N
        sb.append(param.getSimpleName());
        if (it.hasNext()) {
            sb.append(", "); // NOI18N
        }
    }
    sb.append(")"); // NOI18N
    if ( e.getKind() != ElementKind.CONSTRUCTOR ) {
        TypeMirror rt = e.getReturnType();
        if ( rt.getKind() != TypeKind.VOID ) {
            sb.append(" : "); // NOI18N
            sb.append(translateToHTML(print(e.getReturnType())));
        }
    }
    return sb.toString();
}
 
Example 15
Source File: ConfusingVarargsParameter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isVarargsParameter(CompilationInfo ci, TreePath invPath) {
    if (invPath.getLeaf().getKind() != Tree.Kind.METHOD_INVOCATION) {
        return false;
    }
    MethodInvocationTree mit = (MethodInvocationTree)invPath.getLeaf();
    Element e = ci.getTrees().getElement(invPath);
    if (e == null || e.getKind() != ElementKind.METHOD) {
        return false;
    }
    ExecutableElement ee = (ExecutableElement)e;
    return ee.isVarArgs() && mit.getArguments().size() == ee.getParameters().size();
}
 
Example 16
Source File: ValueParser.java    From dataenum with Apache License 2.0 4 votes vote down vote up
static Value parse(Element element, ProcessingEnvironment processingEnv) {
  Messager messager = processingEnv.getMessager();

  if (element.getKind() != ElementKind.METHOD) {
    messager.printMessage(
        Diagnostic.Kind.ERROR,
        String.format(
            "Value specs must be methods, found %s: %s",
            element.getKind().toString().toLowerCase(), element),
        element);
    return null;
  }

  ExecutableElement methodElement = (ExecutableElement) element;
  if (!isValueSpecMarker(methodElement.getReturnType(), processingEnv)) {
    messager.printMessage(
        Diagnostic.Kind.ERROR,
        String.format(
            "Value specs must return dataenum_case, found %s: %s",
            methodElement.getReturnType(), element),
        element);
    return null;
  }

  if (methodElement.getTypeParameters().size() != 0) {
    messager.printMessage(
        Diagnostic.Kind.ERROR,
        String.format(
            "Type parameters must be specified on the top-level interface, found: %s", element),
        element);
    return null;
  }

  if (methodElement.isVarArgs()) {
    messager.printMessage(
        Diagnostic.Kind.ERROR,
        String.format("Vararg parameters not permitted: %s", element),
        element);
    return null;
  }

  List<Parameter> parameters = new ArrayList<>();
  for (VariableElement parameterElement : methodElement.getParameters()) {
    String parameterName = parameterElement.getSimpleName().toString();
    TypeName parameterType = TypeName.get(parameterElement.asType());

    boolean nullable = isAnnotationPresent(parameterElement, ValueParser::isNullableAnnotation);
    boolean redacted = isAnnotationPresent(parameterElement, ValueParser::isRedactedAnnotation);
    Element parameterTypeElement =
        processingEnv.getTypeUtils().asElement(parameterElement.asType());
    boolean isEnum =
        parameterTypeElement != null && parameterTypeElement.getKind() == ElementKind.ENUM;

    parameters.add(new Parameter(parameterName, parameterType, nullable, redacted, isEnum));
  }

  String javadoc = processingEnv.getElementUtils().getDocComment(element);

  if (javadoc != null) {
    javadoc = javadoc.trim();
  }

  String valueSimpleName = methodElement.getSimpleName().toString();
  return new Value(
      valueSimpleName, javadoc, parameters, parseMethodAnnotations(methodElement, messager));
}
 
Example 17
Source File: ELTypeUtilities.java    From netbeans with 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
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private List<? extends TypeMirror> visitMethodOrNew(Tree node, Object p, List<? extends ExpressionTree> args, 
        ExecutableType execType) {
    List<TypeMirror> proposed = new ArrayList<TypeMirror>();
    int[] index = new int[1];
    if (theExpression == null) {
        List<ExecutableElement> methods = org.netbeans.modules.editor.java.Utilities.fuzzyResolveMethodInvocation(info, getCurrentPath(), proposed, index);
        if (methods.isEmpty()) {
            return null;
        } else {
            initExpression(args.get(index[0]));
            return proposed;
        }
    } else {
        Element el = info.getTrees().getElement(getCurrentPath());
        if (el == null) {
            return null;
        }
        if (theExpression.getLeaf() != node &&
            (el.getKind() == ElementKind.METHOD || el.getKind() == ElementKind.CONSTRUCTOR)) {
            int argIndex = args.indexOf(theExpression.getLeaf());
            this.parentExecutable = getCurrentPath();
            TypeMirror argm;
            ExecutableElement ee = (ExecutableElement)el;
            boolean allowEntireVararg = false;
            boolean varargPosition = false;
            if (ee.isVarArgs() && (varargPosition = argIndex >= ee.getParameters().size() -1)) {
                // all parameters after the vararg will be reported at the varargs position. 
                allowEntireVararg = argIndex == ee.getParameters().size() -1;
                argIndex = ee.getParameters().size() - 1;
                if (allowEntireVararg) {
                    this.argIndex = ee.getParameters().size() - 1;
                } else {
                    this.argIndex = ee.getParameters().size();
                }
            } else {
                this.argIndex = argIndex;
            }

            if (execType != null) {
                // handle varargs arguments; if the argtype is a vararg, then either array of the type (reported in argm),
                // or the component can be passed.
                argm = execType.getParameterTypes().get(argIndex);
                // XXX hack
                argm = decapture(argm);
            } else {
                argm = ((ExecutableElement)el).getParameters().get(argIndex).asType();
            }
            if (argm == null || argm.getKind() == TypeKind.ERROR) {
                targetArgType = null;
                return null;
            }
            if (varargPosition && argm.getKind() == TypeKind.ARRAY) {
                TypeMirror ctype = ((ArrayType)argm).getComponentType();
                if (allowEntireVararg) {
                    targetArgType = argm;
                    return Arrays.asList(new TypeMirror[] { argm, ctype });
                }
                argm = ctype;
            }
            targetArgType = argm;
            return Collections.singletonList(argm);
        }
    }
    return null;
}
 
Example 19
Source File: ElementScanningTask.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Creates HTML display name of the Executable element */
private String createHtmlHeader(CompilationInfo info, ExecutableElement e, boolean isDeprecated,boolean isInherited, boolean fqn, TypeElement overridenFrom) {

    StringBuilder sb = new StringBuilder();
    if ( isDeprecated ) {
        sb.append("<s>"); // NOI18N
    }
    if( isInherited ) {
        sb.append( "<font color=" + ui.getInheritedColor() + ">" ); // NOI18N
    }
    Name name = e.getKind() == ElementKind.CONSTRUCTOR ? e.getEnclosingElement().getSimpleName() : e.getSimpleName();
    sb.append(Utils.escape(name.toString()));        
    if ( isDeprecated ) {
        sb.append("</s>"); // NOI18N
    }

    sb.append("("); // NOI18N

    List<? extends VariableElement> params = e.getParameters();
    for( Iterator<? extends VariableElement> it = params.iterator(); it.hasNext(); ) {
        VariableElement param = it.next(); 
        sb.append( "<font color=" + ui.getTypeColor() + ">" ); // NOI18N
        final boolean vararg = !it.hasNext() && e.isVarArgs();
        sb.append(printArg(info, param.asType(),vararg, fqn));
        sb.append("</font>"); // NOI18N
        sb.append(" "); // NOI18N
        sb.append(Utils.escape(param.getSimpleName().toString()));
        if ( it.hasNext() ) {
            sb.append(", "); // NOI18N
        }
    }


    sb.append(")"); // NOI18N

    if ( e.getKind() != ElementKind.CONSTRUCTOR ) {
        TypeMirror rt = e.getReturnType();
        if ( rt.getKind() != TypeKind.VOID ) {
            sb.append(" : "); // NOI18N
            sb.append( "<font color=" + ui.getTypeColor() + ">" ); // NOI18N
            sb.append(print(info, e.getReturnType(), fqn));
            sb.append("</font>"); // NOI18N
        }
    }

    if (!isInherited && overridenFrom != null) {
        sb.append(" ↑ ");   //NOI18N
        sb.append(print(info, overridenFrom.asType(), fqn));
    }

    return sb.toString();
}