December 28, 2009

Call Stack Details in Java

As I get more into Android and back into Java, I wanted to know if there was a way to find out where a method was called from. It seems that the StackTarceElement class can be used to get details about the call stack. I found a great article on this blog showing me how to to do this.

I made one addition to the code found on this blog:


public static String getCallStack(int skip)
{
StringBuilder sb = new StringBuilder();

StackTraceElement[] stackTraceElements =
Thread.currentThread().getStackTrace();

for (int i = 3 + skip ; i<stackTraceElements.length; i++)
{
StackTraceElement ste = stackTraceElements[i];
String classname = ste.getClassName();
String methodName = ste.getMethodName();
int lineNumber = ste.getLineNumber();

sb.append(classname + "." + methodName + ":" + lineNumber + "\r\n");
}

return sb.toString();
}

No comments:

Post a Comment