I want to write a simple visualization of a Java program by displaying the program's method calls as branches of a tree. This could be done quite simply by having the program itself tell the visualization what it is doing, but I want to be able to do this with any Java method/class and not just the ones I modify to do so.
What I need is the ability to watch the methods a program calls and what methods are called within that method and so on. Obviously, stack traces provide exactly this functionality:
java.lang.NullPointerException
at MyClass.mash(MyClass.java:9)
at MyClass.crunch(MyClass.java:6)
at MyClass.main(MyClass.java:3)
So I thought about having the program I want to monitor run in a thread and then just look at that thread's stack. However, the thread class does not really support this. It only supports printing the current stack.
Now I, of course, thought of simply changing the PrintStream of the System class so the thread would print its stack into my PrintStream, but this feels kind of wrong.
Is there a better way to do this? Are there any pre-existing classes/methods I can use?
Also, I'm currently downloading the Java source code, to check how exactly the thread class prints its stack so I could maybe subclass thread and imitate the dumpStack() method with my own getStack() method.