Wednesday, March 15, 2006

Java tip - Get the method call hierarchy

So here's a small tip I learnt recently which I find useful at times. Quite often it is a pain to debug an application. You just want to have a trace from where a particular method was called.

Simply use this


MyClass() {
myMethod() {
new RuntimeException().printStackTrace();


Now whenever myMethod is called; a stack trace will be printed. So you can easily get the hierarchy of the calls made to reach that execution point. Notice that the Exception was not thrown; hence no handling is needed.

1 comment:

camel said...

It's a cool trick indeed.. I'm not sure when they added the following, but this static method does the same thing:


You can guess how that method is implemented :)

For multithreaded programming, a useful trick is getting a stack dump of every thread. On windows you press ctrl-break at the console; in unix you press ctrl-\ from the console, or "kill -3 [pid]". Also see Thread.getAllStackTraces() to get a dump of all threads programmatically.