Thursday, March 18, 2010

How to get the invocation hierarchy in Java?

In Java, we can see the invocation hierarchy sometimes in Java. Especially, the log4j can log the class into log file with package name, method and line even. How can we implement the similar functionality?

First, how can we get the invocation class and method? Stack trace.

StackTraceElment[] ste = new Throwable().getStackSTrace();

In the array of StackTraceElement, we can find the hierarchy of current stack. By this, we can get the invocation map of whole stack.

StackTraceElment APIs:
String getClassName()
Returns the fully qualified name of the class containing the execution point represented by this stack trace element.
String getFileName()
Returns the name of the source file containing the execution point represented by this stack trace element.
int getLineNumber()
Returns the line number of the source line containing the execution point represented by this stack trace element.
String getMethodName()
Returns the name of the method containing the execution point represented by this stack trace element.

In Java 5, The Thread introduced two new methods: getStackTrace() and getAllStackTraces(). Now we don't need to use (new Throwable()).getStackTrace() and by using Thread.getCurrentThread().getStackTrace() to get the stack trace info. Not only doing so, but also we can get stack trace of other threads if we have the enough permission.

No comments: