Reputation: 9616
I have a VariableDeclarationStatement
that I am holding on to by visiting the AST. Would like to find all the references to this local variable in the scope of declaration. This includes the nested blocks in the current scope.
One way to do this is to visit all nodes underneath and collect the statements that has this SimpleName
. But this is too cumbersome. Is there a API in JDT to `find' and return a list of such statements.
Upvotes: 2
Views: 946
Reputation: 3105
You can use the JDT SearchEngine
API to retrieve references to a particular AST node.
IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { yourProject });
//IJavaSearchScope scope = SearchEngine.createWorkspaceScope(); // Use this if you dont have the IProject in hand
SearchPattern searchPattern = SearchPattern.createPattern(field,
IJavaSearchConstants.REFERENCES);
SearchRequestor requestor = new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match) {
System.out.println(match.getElement());
}
};
SearchEngine searchEngine = new SearchEngine();
searchEngine.search(searchParttern,
new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
requestor, new NullProgressMonitor());
I haven't checked, but you can try to give the scope as the IType java element.
IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {iType});
For more details use the below link and navigate to the 'Using the Java search engine' section.
http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.jdt.doc.isv/guide/jdt_int_core.htm
Edit: If dependencies are resolved, you can use the below code to get the java element from the VariableDeclarationNode
:
IVariableBinding binding = variableDeclarationNode.resolveBinding()
IJavaElement variableElement = binding.getJavaElement();
Upvotes: 3