title: Monitoring Java from within Java
body: <p>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.</p>
  
  <p>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:</p>
  
  <pre><code> java.lang.NullPointerException
       at MyClass.mash(MyClass.java:9)
       at MyClass.crunch(MyClass.java:6)
       at MyClass.main(MyClass.java:3)
  </code></pre>
  
  <p>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 <em>printing</em> the current stack.</p>
  
  <p>Now I, of course, thought of simply changing the PrintStream of the System class so the thread would print its stack into <em>my</em> PrintStream, but this feels kind of wrong.</p>
  
  <p>Is there a better way to do this? Are there any pre-existing classes/methods I can use?</p>
  
  <p>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.</p>