I have to find all the methods in a class that use a particular member variable. (like “References” in eclipse but I want to implement using code…)I use AST visitor pattern that visits FieldDeclaration to get the name and type of all the member variables. I also use visitor pattern that visits MethodDeclaration nodes to get the content of each method using getBody(). Now I have the field variable name, type and member method details. I thought I can use a string search on the content of each member method but for a variable name “a”, search may return true for keywords like “class” and others too!!! Is there a way to find the usage of a particular variable corresponding to a fieldDeclaration?? (like Binding or something??) If so, what is the AST Node or Class?
Here’s the code I used…
SimpleNameVisitor simpleNameVisitor=new SimpleNameVisitor();
//SimpleNameVisitor is the visitor pattern for SimpleName
simpleNameVisitor.process(mthd.getMethodBlock());
//mthd is the object that stores method details
for(SimpleName simpName:simpleNameVisitor.getIdentifiers()){
if(varName.contentEquals(simpName.getFullyQualifiedName())){
//varName is the field variable name
System.out.println("MethodName: "+mthd.getName());
return;
}
}
Here’s the code that solved the problem(suggested by wjans;changed equals to contentEquals)
VariableDeclarationFragment fragment = ... ;
IBinding binding = fragment.getName().resolveBinding();
public boolean visitNode(SimpleName simpleName) throws Exception {
if (binding.toString().contentEquals(simpleName.resolveBinding().toString()) {
....
}
}
You can do something like this:
Keep a reference to the binding of your FieldDeclaration,
and use this to compare it with the bindings when visiting SimpleName’s inside your MethodDeclaration