Accessing the caller information of a method in Java code

Sometimes it is nice to access the caller of a method. Doing this is relatively simple, you can use the getStackTrace() method on the current thread. This returns the call stack in reverse order, e.g. the first element is the own call, the second element the direct caller and so on.

The following example demonstrate how to print out a maximum of 4 callers in the current stack trace:

public void aMethod(){
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for (int i = 1; i < stackTraceElements.length && i<=4; i++) {
StackTraceElement stackTraceElement = stackTraceElements[i];
System.out.println(stackTraceElement.getClassName() + " Method "
+ stackTraceElement.getMethodName()); //$NON-NLS-1$


About Lars Vogel

Lars Vogel is the founder and CEO of the vogella GmbH and works as Eclipse and Android consultant, trainer and book author. He is a regular speaker at international conferences, He is the primary author of With more than one million visitors per month this website is one of the central sources for Java, Eclipse and Android programming information.
This entry was posted in Java and tagged . Bookmark the permalink.

3 Responses to Accessing the caller information of a method in Java code

Comments are closed.