8

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.

ialexander
  • 898
  • 10
  • 28

3 Answers3

8

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());
            }
}
ialexander
  • 898
  • 10
  • 28
2

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.

1

Working:

In the visit(FieldDeclaration n, Object arg) method of the VoidVisitorAdapter class, the following can be used for extracting variables.

It will give the exact name of the variables whether initialized or not.

String newstr;
List<VariableDeclarator> list = n.getVariables();
//as getVariables() returns a list we need to implement that way 
for (VariableDeclarator var : list) {

    String item = var.toString();

    if (item.contains("=")) {

        if (item != null && item.length() > 0) {

            int index = item.lastIndexOf("=");
            newstr = item.substring(0, index);
            newstr = newstr.trim();
            variablename = newstr;`
            //variablename is the name of the desired variable.
        }
    } 
}
Pang
  • 9,564
  • 146
  • 81
  • 122