Java Code Examples for com.sun.source.tree.MethodTree#getParameters()

The following examples show how to use com.sun.source.tree.MethodTree#getParameters() . 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: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String createMethodSignature(MethodTree m, boolean skipName) {
    String sign = "";
    if (!skipName) {
        sign += m.getName();
    }
    sign += "(";
    if (m.getParameters() != null) {
        for (VariableTree p : m.getParameters()) {
            sign += getShortTypeName(p.getType()) + ",";
        }
        if (m.getParameters().size() > 0) {
            sign = sign.substring(0, sign.length() - 1);
        }
    }
    sign += ")";
    return sign;
}
 
Example 2
Source File: AsyncConverter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ClassTree moveRestMethod( TreeMaker maker, String movedName,
        MethodTree method, WorkingCopy copy, ClassTree classTree)
{
    List<? extends VariableTree> parameters = method.getParameters();
    Tree returnType = method.getReturnType();
    BlockTree body = method.getBody();  
    
    ModifiersTree modifiers = maker.Modifiers(EnumSet.of(Modifier.PRIVATE));
    MethodTree newMethod = maker.Method(modifiers, movedName, 
            returnType,
            Collections.<TypeParameterTree> emptyList(),
            parameters,
            Collections.<ExpressionTree> emptyList(),body,null);
    
    ClassTree newClass = maker.addClassMember(classTree, newMethod);
    newClass = maker.removeClassMember(newClass, method);
    return newClass;
}
 
Example 3
Source File: TreeConverter.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private TreeNode convertMethodDeclaration(MethodTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  ExecutableElement element = (ExecutableElement) getElement(path);
  MethodDeclaration newNode = new MethodDeclaration();

  // JCMethodDecl's preferred diagnostic position is the beginning of the method name.
  int methodStartPosition = ((JCMethodDecl) node).pos().getPreferredPosition();

  int length =
      ElementUtil.isConstructor(element)
          ? element.toString().indexOf('(')
          : node.getName().length();

  Name name = Name.newName(null /* qualifier */, element);
  name.setPosition(new SourcePosition(methodStartPosition, length));

  convertBodyDeclaration(node, parent, node.getModifiers(), newNode);
  for (VariableTree param : node.getParameters()) {
    newNode.addParameter((SingleVariableDeclaration) convert(param, path));
  }
  return newNode
      .setIsConstructor(ElementUtil.isConstructor(element))
      .setExecutableElement(element)
      .setBody((Block) convert(node.getBody(), path))
      .setName(name);
}
 
Example 4
Source File: MethodInputParametersMustBeFinal.java    From besu with Apache License 2.0 5 votes vote down vote up
private Description matchParameters(final MethodTree tree) {
  for (final VariableTree inputParameter : tree.getParameters()) {
    if (isMissingFinalModifier(inputParameter)) {
      return describeMatch(tree);
    }
  }

  return Description.NO_MATCH;
}
 
Example 5
Source File: UsageCounter.java    From piranha with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitMethod(MethodTree tree, Void unused) {
  Symbol.MethodSymbol mSym = ASTHelpers.getSymbol(tree);
  if (ASTHelpers.hasAnnotation(mSym, "dagger.Provides", state)) {
    for (VariableTree vt : tree.getParameters()) {
      declaredParamVars.put(vt, mSym);
    }
  }
  return super.visitMethod(tree, null);
}
 
Example 6
Source File: JpaControllerUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static ClassTree modifyDefaultConstructor(ClassTree classTree, ClassTree modifiedClassTree, WorkingCopy wc, MethodInfo modifiedConstructorInfo) {
    if (!"<init>".equals(modifiedConstructorInfo.getName())) {
        throw new IllegalArgumentException("modifiedConstructorInfo name must be <init>");
    }
    
    MethodTree modifiedConstructor = createMethod(wc, modifiedConstructorInfo);
    MethodTree constructor = null;
    for(Tree tree : modifiedClassTree.getMembers()) {
        if(Tree.Kind.METHOD == tree.getKind()) {
            MethodTree mtree = (MethodTree)tree;
            List<? extends VariableTree> mTreeParameters = mtree.getParameters();
            if(mtree.getName().toString().equals("<init>") &&
                    (mTreeParameters == null || mTreeParameters.isEmpty()) &&
                    !wc.getTreeUtilities().isSynthetic(wc.getTrees().getPath(wc.getCompilationUnit(), classTree))) {
                    constructor = mtree;
                    break;
            }
        }
    }
    if (constructor == null) {
        modifiedClassTree = wc.getTreeMaker().addClassMember(modifiedClassTree, modifiedConstructor);
    }
    else {
        wc.rewrite(constructor, modifiedConstructor);
    }
    return modifiedClassTree;
}
 
Example 7
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 8
Source File: JavadocUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isInHeader(CompilationInfo info, MethodTree tree, int offset) {
    CompilationUnitTree cut = info.getCompilationUnit();
    SourcePositions sp = info.getTrees().getSourcePositions();
    long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree);
    
    List<? extends ExpressionTree> throwz;
    List<? extends VariableTree> params;
    List<? extends TypeParameterTree> typeparams;
    
    if ((throwz = tree.getThrows()) != null && !throwz.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, throwz.get(throwz.size() - 1));
    } else if ((params = tree.getParameters()) != null && !params.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, params.get(params.size() - 1));
    } else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1));
    } else if (tree.getReturnType() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getReturnType());
    } else if (tree.getModifiers() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers());
    }
    
    TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree);
    
    ts.move((int) lastKnownOffsetInHeader);
    
    while (ts.moveNext()) {
        if (ts.token().id() == JavaTokenId.LBRACE || ts.token().id() == JavaTokenId.SEMICOLON) {
            return offset < ts.offset();
        }
    }
    
    return false;
}
 
Example 9
Source File: MethodArgumentsScanner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public MethodArgument[] visitMethod(MethodTree node, Object p) {
    long startMethod = positions.getStartPosition(tree, node);
    long endMethod = positions.getEndPosition(tree, node);
    if (methodInvocation || startMethod == Diagnostic.NOPOS || endMethod == Diagnostic.NOPOS ||
                            !(offset >= lineMap.getLineNumber(startMethod) &&
                             (offset <= lineMap.getLineNumber(endMethod)))) {
        return super.visitMethod(node, p);
    }
    List<? extends VariableTree> args = node.getParameters();
    List<? extends TypeParameterTree> argTypes = node.getTypeParameters();
    int n = args.size();
    arguments = new MethodArgument[n];
    for (int i = 0; i < n; i++) {
        VariableTree var = args.get(i);
        long startOffset = positions.getStartPosition(tree, var);
        long endOffset = positions.getEndPosition(tree, var);
        if (startOffset == Diagnostic.NOPOS || endOffset == Diagnostic.NOPOS) {
            return new MethodArgument[] {};
        }
        arguments[i] = new MethodArgument(var.getName().toString(),
                                          var.getType().toString(),
                                          positionDelegate.createPosition(
                                            (int) startOffset,
                                            (int) lineMap.getLineNumber(startOffset),
                                            (int) lineMap.getColumnNumber(startOffset)),
                                          positionDelegate.createPosition(
                                            (int) endOffset,
                                            (int) lineMap.getLineNumber(endOffset),
                                            (int) lineMap.getColumnNumber(endOffset)));
    }
    return arguments;
    //return composeArguments(args, argTypes);
}
 
Example 10
Source File: UTemplater.java    From Refaster with Apache License 2.0 5 votes vote down vote up
public static ImmutableMap<String, VarSymbol> freeExpressionVariables(
    MethodTree templateMethodDecl) {
  ImmutableMap.Builder<String, VarSymbol> builder = ImmutableMap.builder();
  for (VariableTree param : templateMethodDecl.getParameters()) {
    builder.put(param.getName().toString(), ASTHelpers.getSymbol(param));
  }
  return builder.build();
}
 
Example 11
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 5 votes vote down vote up
@Override
public MethodModel visitMethod(MethodTree node, VisitContext p) {
  List<TypeInfo> parameterTypes = new ArrayList<>();
  for (VariableTree var : node.getParameters()) {
    JCTree.JCVariableDecl decl = (JCTree.JCVariableDecl) var;
    TypeInfo parameterType = factory.create(decl.sym.asType());
    parameterTypes.add(parameterType);
  }
  TypeInfo returnType = VoidTypeInfo.INSTANCE;
  if (node.getReturnType() instanceof JCTree) {
    returnType = factory.create(((JCTree)node.getReturnType()).type);
  }
  return new MethodModel("" + typeElt.getQualifiedName(), scan(node.getBody(), p), new MethodSignature(node.getName().toString(), parameterTypes, false, returnType), node.getParameters().stream().map(param -> param.getName().toString()).collect(Collectors.toList()));
}
 
Example 12
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
static MethodSignature create(
    CompilationUnitTree compilationUnitTree, MethodTree tree, Trees trees) {
  ImmutableList.Builder<Equivalence.Wrapper<TypeMirror>> parameterTypes =
      ImmutableList.builder();
  for (VariableTree parameter : tree.getParameters()) {
    parameterTypes.add(
        MoreTypes.equivalence()
            .wrap(trees.getTypeMirror(trees.getPath(compilationUnitTree, parameter))));
  }
  return new AutoValue_TreeDiffer_MethodSignature(
      tree.getName().toString(), parameterTypes.build());
}
 
Example 13
Source File: JSNI2JavaScriptBody.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    Token<JavaTokenId> jsniComment = findBlockToken(ctx.getWorkingCopy(), ctx.getPath(), null);

    if (jsniComment == null) {
        //XXX: warn?
        return ;
    }

    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    MethodTree mt = (MethodTree) ctx.getPath().getLeaf();
    List<LiteralTree> params = new ArrayList<LiteralTree>();

    for (VariableTree p : mt.getParameters()) {
        params.add(make.Literal(p.getName().toString()));
    }

    String body = jsniComment.text().toString().replace("\"", "\\\"");
    body = body.replace("/*-{", "").replace("}-*/", "");

    List<ExpressionTree> arr = new ArrayList<ExpressionTree>();
    arr.add(make.Assignment(make.Identifier("args"), make.NewArray(null, Collections.<ExpressionTree>emptyList(), params)));
    if (body.contains("@") && body.contains("::")) {
        arr.add(make.Assignment(make.Identifier("javacall"), make.Literal(true)));
    }
    final String[] lines = body.split("\n");
    StringBuilder jsB = new StringBuilder();
    String sep = "\"";
    for (int i = 0; i < lines.length; i++) {
        String line = lines[i];
        if (i < lines.length - 1) {
            line = line + "\\n";
        }
        jsB.append(sep).append(line).append("\"");
        sep = " + \n\"";
    }
    arr.add(make.Assignment(make.Identifier("body"), make.Identifier(jsB.toString())));

    AnnotationTree jsBody = make.Annotation(make.QualIdent("net.java.html.js.JavaScriptBody"), arr);
    ctx.getWorkingCopy().rewrite(mt.getModifiers(), make.addModifiersAnnotation(mt.getModifiers(), jsBody));
}
 
Example 14
Source File: JaxWsClassesCookieImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@org.netbeans.api.annotations.common.SuppressWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
@Override
public void addOperation(final MethodTree method) {
    JavaSource targetSource = JavaSource.forFileObject(implClassFO);
    CancellableTask<WorkingCopy> modificationTask = 
        new CancellableTask<WorkingCopy>() 
        {
        @Override
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);            
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree javaClass = SourceUtils.
                getPublicTopLevelTree(workingCopy);
            if (javaClass!=null) {
                GenerationUtils genUtils = GenerationUtils.newInstance(
                            workingCopy);
                
                AnnotationTree webMethodAnnotation = make.Annotation(
                    make.QualIdent("javax.jws.WebMethod"),      //NOI18N
                    Collections.<ExpressionTree>emptyList()
                );
                // add @WebMethod annotation
                ModifiersTree modifiersTree = make.addModifiersAnnotation(
                        method.getModifiers(), webMethodAnnotation);
                
                // add @Oneway annotation
                if (Kind.PRIMITIVE_TYPE == method.getReturnType().getKind()) {
                    PrimitiveTypeTree primitiveType = 
                        (PrimitiveTypeTree)method.getReturnType();
                    if (TypeKind.VOID == primitiveType.getPrimitiveTypeKind()) {
                        AnnotationTree oneWayAnnotation = make.Annotation(
                            make.QualIdent("javax.jws.Oneway"),         // NOI18N
                            Collections.<ExpressionTree>emptyList()
                        );
                        modifiersTree = make.addModifiersAnnotation(
                                modifiersTree, oneWayAnnotation);
                    }
                }
                
                // add @WebParam annotations 
                List<? extends VariableTree> parameters = method.getParameters();
                List<VariableTree> newParameters = new ArrayList<VariableTree>();
                for (VariableTree param:parameters) {
                    AnnotationTree paramAnnotation = make.Annotation(
                        make.QualIdent("javax.jws.WebParam"),           //NOI18N
                        Collections.<ExpressionTree>singletonList(
                            make.Assignment(make.Identifier("name"),    //NOI18N
                                    make.Literal(param.getName().toString()))) 
                    );
                    newParameters.add(genUtils.addAnnotation(param, paramAnnotation));
                }
                // create new (annotated) method
                MethodTree  annotatedMethod = make.Method(
                            modifiersTree,
                            method.getName(),
                            method.getReturnType(),
                            method.getTypeParameters(),
                            newParameters,
                            method.getThrows(),
                            method.getBody(),
                            (ExpressionTree)method.getDefaultValue());
                Comment comment = Comment.create(NbBundle.getMessage(
                        JaxWsClassesCookieImpl.class, "TXT_WSOperation"));      //NOI18N                 
                make.addComment(annotatedMethod, comment, true);
                
                ClassTree modifiedClass = make.addClassMember(javaClass,
                        annotatedMethod);
                workingCopy.rewrite(javaClass, modifiedClass);
            }
        }
        @Override
        public void cancel() {
            
        }
    };
    try {
        targetSource.runModificationTask(modificationTask).commit();
    } catch (IOException ex) {
        ErrorManager.getDefault().notify(ex);
    }
}
 
Example 15
Source File: AsyncConverter.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private ClassTree createAsyncMethod( TreeMaker maker,
        String asyncName, String service, MethodTree method, String movedName , 
        WorkingCopy copy, ClassTree classTree, boolean isEjb)
{
    ModifiersTree modifiers = method.getModifiers();
    if ( isEjb ){
        AnnotationTree async = maker.Annotation(maker.QualIdent(
                "javax.ejb.Asynchronous"),          // NOI18N 
                Collections.<ExpressionTree>emptyList());
        modifiers  = maker.addModifiersAnnotation(modifiers, async);
    }
    List<? extends VariableTree> parameters = method.getParameters();
    String asyncReponseParam = getAsynParam("asyncResponse",parameters);//NOI18N
    
    ModifiersTree paramModifier = maker.Modifiers(EnumSet.of(Modifier.FINAL));
    AnnotationTree annotation = maker.Annotation(
            maker.QualIdent("javax.ws.rs.container.Suspended"),        // NOI18N
            Collections.<ExpressionTree>emptyList());
    paramModifier = maker.Modifiers(paramModifier, 
            Collections.singletonList(annotation));
    VariableTree asyncParam = maker.Variable(paramModifier, asyncReponseParam, 
            maker.QualIdent("javax.ws.rs.container.AsyncResponse"), null);//NOI18N
    List<VariableTree> params = new ArrayList<VariableTree>(parameters.size()+1);
    params.add(asyncParam);
    
    Tree returnType = method.getReturnType();
    boolean noReturn =returnType.toString().equals("void");     // NOI18N

    StringBuilder body = new StringBuilder("{");                // NOI18N
    if ( !isEjb ){
        body.append(service);
        body.append(".submit(new Runnable() { public void run() {");//NOI18N
    }
    if ( !noReturn ){
        body.append(asyncReponseParam);
        body.append(".resume(");                            // NOI18N
    }
    body.append(movedName);
    body.append('(');
    for (VariableTree param : parameters) {
        ModifiersTree modifier = maker.addModifiersModifier(param.getModifiers(), 
                Modifier.FINAL);
        VariableTree newParam = maker.Variable(modifier, param.getName(), 
                param.getType(), param.getInitializer());
        params.add(newParam);
        TreePath pathParam = copy.getTrees().getPath(
                copy.getCompilationUnit(), param);
        body.append(copy.getTrees().getElement(pathParam).getSimpleName());
        body.append(',');
    }
    if ( !parameters.isEmpty()){
        body.deleteCharAt(body.length()-1);
    }
    if ( noReturn){
        body.append(");");
        body.append(asyncReponseParam);
        body.append(".resume(javax.ws.rs.core.Response.ok().build());");//NOI18N
    }
    else {
        body.append("));");
    }
    if ( !isEjb ){
        body.append("}});");
    }
    body.append('}');
    
    MethodTree newMethod = maker.Method(modifiers, asyncName, 
            maker.Type("void"),             // NOI18N
            Collections.<TypeParameterTree> emptyList(),
            params,
            Collections.<ExpressionTree> emptyList(),
            body.toString(),null);
    return maker.addClassMember(classTree, newMethod);
}
 
Example 16
Source File: ASTPathCriterion.java    From annotation-tools with MIT License 4 votes vote down vote up
private boolean checkNull(List<Tree> path, int ix) {
    Tree node = path.get(path.size()-1);
    int last = astPath.size() - 1;
    ASTPath.ASTEntry entry = astPath.get(ix);
    Tree.Kind kind = entry.getTreeKind();

    switch (kind) {
    // case ANNOTATION:
    // case INTERFACE:
    case CLASS:  // "extends" clause?
        return ASTPath.isClassEquiv(kind)
                && ix == last && entry.getArgument() == -1
                && entry.childSelectorIs(ASTPath.BOUND);
    case TYPE_PARAMETER:
        return node.getKind() == Tree.Kind.TYPE_PARAMETER
                && ix == last && entry.getArgument() == 0
                && entry.childSelectorIs(ASTPath.BOUND);
    case METHOD:  // nullary constructor? receiver?
        if (node.getKind() != Tree.Kind.METHOD) { return false; }
        MethodTree method = (MethodTree) node;
        List<? extends VariableTree> params = method.getParameters();
        if ("<init>".equals(method.getName().toString())) {
            if (ix == last) { return true; }
            ASTPath.ASTEntry next = astPath.get(++ix);
            String selector = next.getChildSelector();
            Tree typeTree =
                ASTPath.TYPE_PARAMETER.equals(selector)
                    ? method.getTypeParameters().get(next.getArgument())
              : ASTPath.PARAMETER.equals(selector)
                    ? params.get(next.getArgument()).getType()
              : null;
            return typeTree != null && checkTypePath(ix, typeTree);
        } else if (entry.childSelectorIs(ASTPath.PARAMETER)
                && entry.getArgument() == -1) {
            if (ix == last) { return true; }
            VariableTree rcvrParam = method.getReceiverParameter();
            if (rcvrParam == null) {  // TODO
              // ClassTree clazz = methodReceiverType(path);
              // return checkReceiverType(ix,
              //    ((JCTree.JCClassDecl) clazz).type);
            } else {
              return checkTypePath(ix+1, rcvrParam.getType());
            }
        }
        return false;
    case NEW_ARRAY:
        if (node.getKind() != Tree.Kind.NEW_ARRAY) { return false; }
        NewArrayTree newArray = (NewArrayTree) node;
        int arg = entry.getArgument();
        if (entry.childSelectorIs(ASTPath.TYPE)) {
            if (ix == last) { return true; }
            // Tree t = newArray.getType();
            // int depth = 1;
            // while (t.getKind() == Tree.Kind.ARRAY_TYPE) {
            //    t = ((ArrayTypeTree) t).getType();
            //    ++depth;
            // }
            return arg == arrayDepth(newArray);
        } else {
            List<? extends ExpressionTree> typeTrees =
                    entry.childSelectorIs(ASTPath.DIMENSION)
                            ? newArray.getDimensions()
                  : entry.childSelectorIs(ASTPath.INITIALIZER)
                            ? newArray.getInitializers()
                  : null;
            return typeTrees != null && arg < typeTrees.size()
                  && checkTypePath(ix+1, typeTrees.get(arg));
        }
    case UNBOUNDED_WILDCARD:
        return isBoundableWildcard(path, path.size()-1);
    default:  // TODO: casts?
        return false;
    }
}