How could I search references to a field on a AST or a CompilationUnit in eclipse?

会有一股神秘感。 提交于 2020-01-05 08:42:32

问题


Hi,

I'm developing an Eclipse plugin. I need to find all the references in the source using AST's or jdt.core.dom or something like that. I need this references like ASTNodes in order to get the parent node and check several things in the expression where references are involved. Thanks beforehand.


Edited:

I want to concrete a little more, My problem is that I try to catch some references to a constant but... I have not idea how I can do to catch in the matches this references. I need check the expressions which the references to a determined constant are involved. I only get the source of the method where they are used.

I think the problem is the scope or the pattern:

pattern = SearchPattern.createPattern(field, IJavaSearchConstants.REFERENCES);


scope = SearchEngine.createJavaSearchScope(declaringType.getMethods());

Thanks beforehand!


回答1:


I used something like:

  1. Search for the declaration of an method, returns an IMethod
  2. Search for references to the IMethod, record those IMethods
  3. For each IMethod returned, create an AST from its compilation unit

Searching for declarations or references looks like the following code.

SearchRequestor findMethod = ...; // do something with the search results
SearchEngine engine = new SearchEngine();
IJavaSearchScope workspaceScope = SearchEngine.createWorkspaceScope();
SearchPattern pattern = SearchPattern.createPattern(searchString,
            IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS,
            SearchPattern.R_EXACT_MATCH);
SearchParticipant[] participant = new SearchParticipant[] { SearchEngine
            .getDefaultSearchParticipant() };
engine.search(pattern, participant, workspaceScope, findMethod,
                monitor);

Once you have your IMethod references, you can get to the AST using:

ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setResolveBindings(true);
if (methodToSearch.isBinary()) {
    parser.setSource(methodToSearch.getClassFile());
} else {
    parser.setSource(methodToSearch.getCompilationUnit());
}
CompilationUnit cu = (CompilationUnit) parser.createAST(null);

See http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.jdt.doc.isv/guide/jdt_int_core.htm for more details on java search, the java model, and the AST.



来源:https://stackoverflow.com/questions/5887132/how-could-i-search-references-to-a-field-on-a-ast-or-a-compilationunit-in-eclips

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!