问题
I'm using JDT AST to parse a given source. I want to find the references of a given object/variable when it triggers the relavant visitor when using AST. E.g.: Consider the following code:
public class SampleClass {
public void printMe(){
System.out.println("hello");
}
public static void main(String a[]){
SampleClass s =new SampleClass();
// do some other work
s.printMe();
}
}
When I'm parsing the above code, when it comes to the variable declaration of "s", it will call the visitor method of "VariableDeclarationFragment" type. At that point I want to find out all the references of variable "s" before going to visit rest of the code lines. Is this possible? I thought of using JDT SearchEngine and call at that point to resolve the references separately. But wasn't successful. Can I do it by only using AST itself?
Please note that I'm using JDT AST in a stand-alone program and not as a Eclipse plugin project. I'm bit confused whether I can use the SearchEngine in that case as it couldnt resolve IJava* types for a given code unit (class,method etc.). Please share your expertise to sort out this.
回答1:
Using the search engine is overkill. The search engine is meant for cross file searching. And, without the workbench started (ie- without an Eclipse instance in the background) you cannot use the search engine.
It looks like you only want to find references to variables in the same file. Your best bet here is to create a visitor that will visit the entire file and look for references to the variable. Since these are variables and their scope doesn't escape the method they are declared in, you only need to visit that method.
Something like this:
class MyVariableVisitory extends ASTVisitor {
public boolean visit(SimpleName node) {
if (node.getIdentifier().equals(variableToLookFor)) {
acceptMatch(node);
}
return true;
}
}
Since you are only looking for references to variables, you only need to look at Name
ast nodes.
来源:https://stackoverflow.com/questions/14012331/can-i-use-jdt-search-engine-while-parsing-a-source-from-jdt-ast