简体   繁体   中英

Visit all method calls deep down starting from method with JDT

I need to parse java method, looking inside all other method calls inside it (and inside them and deeper and so on) in order to find all occurences of some string, let say "System.out.println ("Blabla");"

How can I use JDT ( http://www.programcreek.com/2011/01/best-java-development-tooling-jdt-and-astparser-tutorials ) for that and what are the other alternatives?

If I have a code like this:

public void A() {

    "System.out.println ("Blabla");
    B();        

}

public void B() {

    "System.out.println ("Blabla");
    C();

}

public void C() {

    "System.out.println ("Blabla");

}

I would like just to specify the name of the method ("A") and as an output I want:

"System.out.println ("Blabla");
"System.out.println ("Blabla");
"System.out.println ("Blabla");

You want to do that by hand or programmatically?

I would suggest using the Open Call Hierarchy option in Eclipse, just press Ctrl + Alt + H to check if that's what you need. It traces back all the way up where the given method is called. If you're familiar with JDT, you must have some experience in how to find the implementation of that Eclipse feature so you can analyze it further (I'd suggest using the Plug-in Spy ).

Hope that helps something.

This is possible with JDT/AST. I have done similar things. My favorite approach is to create a plugin for Eclipse and process files (compilation units) inside of the projects.

The basic steps to follow are:

  1. You can use AST to parse the code (ie of a JDT ICompilationUnit) into an AST model.

  2. You can then use the visitor pattern to find the MethodDeclaration you want to start your search.

  3. Once you have that, you can use the visitor again on the MethodDeclaration to find all MethodInvocations inside the method body.

  4. The binding of the MethodInvocation will point you to the MethodDeclaration pf the method beeing called. (Be sure to enable bindings while parsing.)

A realy nice tool to use, when working with AST, is the AST View. It shows you the AST model of files opened with the Eclipse Java editor. You can install the AST View from this update site: http://www.eclipse.org/jdt/ui/update-site

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM