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()
Hi!
I blogged about this more than 2 years ago, and was then told by someone that it was an old well known trick. I guess there’s always someone else ahead…
http://www.jroller.com/page/matsh/20030221#how_to_do_c_friends
In Java 1.5 you don’t need to create Throwable anymore (expensive operation), use Thread.getStackTrace() instead.