Kasun Karunarathna
Kasun Karunarathna

Reputation: 135

Getting the methods called inside main method using JavaParser

I am using the JavaParser library to parse the java code and access the java code tokens.

Following is my code

import java.util.Vector;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;
import com.github.javaparser.ast.stmt.BlockStmt;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;


public class MethodParser {
    public static void main(String[] args) throws Exception {
        // creates an input stream for the file to be parsed

        FileInputStream in = new FileInputStream("F:\\Projects\\Parse.java");

        CompilationUnit cu;
        try {
            // parse the file
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }
        cu.accept(new MethodVisitor(), null);
    }
    private static class MethodVisitor extends VoidVisitorAdapter<Void> {
        @Override

 public void visit(MethodDeclaration n, Void arg) {
            /* here you can access the attributes of the method.
             this method will be called for all methods in this
             CompilationUnit, including inner class methods */

            String x =String.valueOf(n.getBody() );

            n.ifAssertStmt(n);

            System.out.println(x);
            super.visit(n, arg);
        }
        public void visitVariables(MethodDeclaration n, Void arg) {


            String x =String.valueOf(n.getBody());
            System.out.println(x);
            super.visit(n, arg);
        }

    }

}

following is the code of the java file read by the JavaParser (Parse.java)

public class Parse{

public void printFirstName(){
System.out.println("My First name is John");
}

public void printLastName(){
System.out.println("My Last name is John");
}


public static void main(String[] args){

Parse A = new Parse();
A.printFirstName();

}
}

The out put prints the contents of all the method bodies in the parse.java class. But I want to get the methods called in the main method( i.e printFirstName in this scenario) How can I do it?

Upvotes: 1

Views: 2499

Answers (1)

Federico Tomassetti
Federico Tomassetti

Reputation: 2248

I would use a visitor and: 1) set a flag in visitMethodDeclaration checking if the method you are visiting is main (name, static flag, type of parameters) 2) in the visitMethodCallExpression method I woul print the calls only if the flag at point 1 was set

Upvotes: 5

Related Questions