How do I find the caller of a method using stacktrace or reflection?

Sathish picture Sathish · Jan 7, 2009 · Viewed 271.7k times · Source

I need to find the caller of a method. Is it possible using stacktrace or reflection?

Answer

Adam Paynter picture Adam Paynter · Jan 7, 2009
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()

According to the Javadocs:

The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

You will have to experiment to determine which index you want (probably stackTraceElements[1] or [2]).