Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call tree of a method: how coverage tools work in Java? Is there an API?

I'm looking for a way to list all the methods called (a call tree) by another method, during java runtime.

I'm looking for an api or an output that could allow me to use the data with a script.

Any ideas?

Thx

like image 297
Eric V Avatar asked Aug 30 '11 00:08

Eric V


2 Answers

Coverage and profiling tools mostly employ two techniques : polling periodically the JVM for the state of various threads or instrumenting application bytecode to push out of the JVM relevant data.

There is no direct API support in the java language itself, however there are many tools you can exploit :

  1. You can catch thread dumps, using jstack or similar tools, save them toa file, then analyze (or write a script/program to analyze), this is polling.
  2. Use ASM or BCEL to modify bytecode of your application, this is push but is very hard to do.
  3. Use AspectJ, using the load time weaving agent it's just a command line parameter to enable it.

Solution 3 is by far easier, clean and versatile.

To print, at runtime, whatever method is called as a consequence of the execution of a method is a simple tracing aspect, something similar to :

public aspect TraceCalls {
  pointcut aCall : call(* *(..));
  pointcut inside : cflow(execution(public MyClass.MyMethod(..)));
  before() : aCall() && inside() {
    System.out.println(thisJoinPoint);
  }
}

Obviously, you can access much more data, print them in a file, format it etc...

(Please note that I wrote this code here, so it could be full of syntax errors)

like image 184
Simone Gianni Avatar answered Oct 12 '22 13:10

Simone Gianni


Well...it's a good question in the first place...I highly doubt if there is any such utility available in the market...however, there are ways to get around this...like using a debugger tool in one of your favorite IDEs like Eclipse and Netbeans...

like image 25
Vishwas Shashidhar Avatar answered Oct 12 '22 14:10

Vishwas Shashidhar