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 vogella.com. 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

  1. Is there a performance penalty to accessing the stack-trace?

  2. Lars Vogel says:

    Alternatively you can use SecurityManager which is much faster. Thanks to Gunnar Morling for the tip via Twitter.

    public class CallerProvider extends SecurityManager {

    public Class getCallerClass() {
    return getClassContext()[2];
    }
    }

  3. Kevin Biger says:

    Funny thing about Thread.currentThread().getStackTrace() , it return (new Exception()).getStackTrace() as you can see there :
    http://hg.openjdk.java.net/jdk6/jdk6/jdk/file/5672a2be515a/src/share/classes/java/lang/Thread.java

Comments are closed.