Accessing the caller information of a method in Java code

less than 1 minute read

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());