I am using JavaParser to parse Java applications. I need a function to return the number of cases that a variable in a method body is read or modified. As an example, the function should determines variable x in the below code is read two times and one time is modified.
private int foo(){
int x;
System.out.println(x); //Read
x = 10; //modify
bar(x); //read
}
so far I wrote this code.
for (ClassOrInterfaceDeclaration cd : cu.findAll(ClassOrInterfaceDeclaration.class)) {
for (MethodDeclaration method : cd.getMethods()) {
method.getBody().ifPresent(blockStatement -> {
for( VariableDeclarator variable : blockStatement.findAll(VariableDeclarator.class)) {
for (NameExpr nameExp : blockStatement.findAll(NameExpr.class)) {
if (nameExp.getNameAsString().equals(variable.getNameAsString())) {
System.out.println(nameExp.getNameAsString());
}
}
}
});
}
}
Using this code I can know the variable x is used three times in the method body, but I can not distinguish between read and write. Let me know what is the best way to do this using JavaParser.