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 just want a list of all variables from a java source, regardless of scope.

+6
source share
3 answers

The solution was to create a visitor class that extends the VoidVisitorAdapter and overrides 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()); } } 
+8
source

Please note that based on your decision, the initial list of fields can be made using the following code:

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

Remember to call super.visit if you override several visiting methods in the visitor’s adapter.

+2
source

IN:

In the visit(FieldDeclaration n, Object arg) method visit(FieldDeclaration n, Object arg) of the VoidVisitorAdapter class, you can use the following to retrieve the variables.

It will give the exact name of the variables, 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. } } } 
0
source

All Articles