I would like to retrieve all variable names in all methods of a java file. Example Like a Person.java contains
class Person {
private String firstName;
private String lastName;
public static void main() {
String test = "test";
Person p1 = new Person();
p1.setName("John");
}
public void setName(String name) {
this.firstName = name;
}
}
i would like to be able to print out all variables declared. I have tried using javaparser to retrieve them. However, i can only retrieve variables declared in the class which is
firstName
lastName
I want to be able to retrieve all variables declared in main method as well
firstName
lastName
test
My javaparser method is
public static void getVariables(String inputFilePath) {
try {
CompilationUnit cu = StaticJavaParser.parse(new File(inputFilePath));
cu.findAll(FieldDeclaration.class).forEach(field -> {
field.getVariables().forEach(variable -> {
System.out.println(variable.getName());
variable.getInitializer().ifPresent(initValue ->
System.out.println(initValue.toString()));
});
});
} catch (FileNotFoundException fe) {
System.out.println(fe.getMessage());
} catch (IOException e){
System.out.println(e.getMessage());
}
}
Solved
As following Eugene's suggestion, i am able to retrieve all variables now
public static void getVariables(String inputFilePath) {
try {
CompilationUnit cu = StaticJavaParser.parse(new File(inputFilePath));
cu.findAll(VariableDeclarator.class).forEach(variable -> {
System.out.println(variable);
});
} catch (FileNotFoundException fe) {
} catch (IOException e) {
}
}