Who is calling me? – Analyzing the Java Callstack

Lucas Jellema 2
0 0
Read Time:57 Second

During the Spring Workshop, Rod Johnson started a brief discussion on how to find out in a Java Class who invoked the method currently being executed. The best trick: create a new Throwable and inspect the stacktrace. In Java 1.3 you had to use the printstackTrace() method and parse the String, in Java 1.4 there is the StackTraceElement[] that you can inspect. A simple utility class that informs any caller about his own caller could look like this:

public static String whoCalledMe()
	{
		 Throwable t = new Throwable();
		 return t.getStackTrace()[2].toString();
	}

or:

public static Class whoCalledMe()
	{
		 Throwable t = new Throwable();
		 return t.getStackTrace()[2].getClass(); // that is: Class, not Object!
	}

example code:

/*
 * Created on Jun 10, 2005
 *
 */
package nl.amis.util;

/**
 * @author Lucas
 *
 */
public class CallStackUtils {

	public static String whoCalledMe()
	{
		 Throwable t = new Throwable();
		 return t.getStackTrace()[2].toString();
	}

	public String getCall() {
		return whoCalledMe();
	}

	public String inBetween() {
		return getCall();
	}

	public static void main(String[] args) {

		CallStackUtils call = new CallStackUtils();
		System.out.println(call.inBetween());
	}
}

The output of running main is: nl.amis.util.CallStackUtils.inBetween(CallStackUtils.java:24)

Methods on StackTraceElement include: isNativeMethod() getLineNumber() getClass() getMethodName() getFileName() getClassName()

About Post Author

Lucas Jellema

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director and Oracle Developer Champion. Solution architect and developer on diverse areas including SQL, JavaScript, Kubernetes & Docker, Machine Learning, Java, SOA and microservices, events in various shapes and forms and many other things. Author of the Oracle Press book Oracle SOA Suite 12c Handbook. Frequent presenter on user groups and community events and conferences such as JavaOne, Oracle Code, CodeOne, NLJUG JFall and Oracle OpenWorld.
Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

2 thoughts on “Who is calling me? – Analyzing the Java Callstack

Comments are closed.

Next Post

My First AJAX - the simplest Asynchronuous JavaScript Server call man can imagine

Inspired by Aino’s post AJAX and RIA, I wanted to get my first XMLHttpRequest object based AJAX example getting up and running. It is a standalone HTML page that can be deployed on any webserver (I ran it from inside JDeveloper). When the Submit button is pressed, the page itself […]
%d bloggers like this: