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.
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());
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With