Oct
13
|
The StackTraceElement class can be used to get details about the call stack.
The following example shows how it can be used to view the call stack and determine where a method was called from.
public class WhoCalledMe { public static void main(String[] args) { f(); } public static void f() { g(); } public static void g() { showCallStack(); System.out.println(); System.out.println( "g() was called by "+whoCalledMe()); } public static String whoCalledMe() { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); StackTraceElement caller = stackTraceElements[4]; String classname = caller.getClassName(); String methodName = caller.getMethodName(); int lineNumber = caller.getLineNumber(); return classname+"."+methodName+":"+lineNumber; } public static void showCallStack() { StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); for (int i=2 ; i<stackTraceElements.length; i++) { StackTraceElement ste = stackTraceElements[i]; String classname = ste.getClassName(); String methodName = ste.getMethodName(); int lineNumber = ste.getLineNumber(); System.out.println( classname+"."+methodName+":"+lineNumber); } } }
Array ( ) 3 Responses to “Can I get details of the call stack in Java, such as to find where a method was called from?”
Leave a Reply
You must be logged in to post a comment.
April 22nd, 2010 at 3:15 am
Great code snippet! Works out of the box and displays the concepts very well.
Thank you!
Cheers,
Olaf
March 5th, 2011 at 7:01 am
Really great stuff, thanks!!! Helped me figure out things in some olllldddd legacy code…
March 5th, 2011 at 10:12 am
Glad it helped