Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to parse variables using JavaParser?

Using JavaParser I can get a list of my methods and fields using:

//List of all methods
System.out.println("Methods: " + this.toString());
List<TypeDeclaration> types = n.getTypes();
for (TypeDeclaration type : types)
{
    List<BodyDeclaration> members = type.getMembers();
    for (BodyDeclaration member : members)
    {
        if (member instanceof MethodDeclaration)
        {
            MethodDeclaration method = (MethodDeclaration) member;
            System.out.println("Methods: " + method.getName());
        }
    }
}

//List all field variables.
System.out.println("Field Variables: " + this.toString());
List<TypeDeclaration> f_vars = n.getTypes();
for (TypeDeclaration type : f_vars)
{
    List<BodyDeclaration> members = type.getMembers();
    for (BodyDeclaration member : members)
    {
        if (member instanceof FieldDeclaration)
        {
            FieldDeclaration myType = (FieldDeclaration) member;
            List <VariableDeclarator> myFields = myType.getVariables();
            System.out.println("Fields: " + myType.getType() + ":" + myFields.toString());
        }
    }
}

But I can't figure out how to get a list of my variables. I simply want a list of all variables from a java source, regardless of scope.

like image 245
ialexander Avatar asked Dec 20 '12 11:12

ialexander


2 Answers

The solution was to create a visitor class that extends VoidVisitorAdapter and override the visit() method. Code follows:

@Override
public void visit(VariableDeclarationExpr n, Object arg)
{      
    List <VariableDeclarator> myVars = n.getVars();
        for (VariableDeclarator vars: myVars){
            System.out.println("Variable Name: "+vars.getId().getName());
            }
}
like image 194
ialexander Avatar answered Oct 16 '22 17:10

ialexander


Note that based on your solution, the original field listing can be done with the following code:

@Override
public void visit(FieldDeclaration n, Object arg) {
    System.out.println(n);
    super.visit(n, arg);
}

Don't forget to call super.visit, if you are overriding multiple visit methods in a visitor adapter.

like image 45
Csákvári Dávid Avatar answered Oct 16 '22 17:10

Csákvári Dávid