Java Tip: Who called me?

This can be a handy tip if you are debugging some java application which cannot be run in single step debug for some reason. Suppose you have a method which is called from many places and you need to know the current caller.
Just capture the current stack trace by making a Throwable object. Now get the 2nd stack trace element from t.getStackTrace() which will have the caller details.

A small example..

public class test {

public static void main(String[] args) {
caller1();
caller2();
}

private static void caller1() {
method();
}

private static void caller2() {
method();
}

private static void method() {
Throwable t = new Throwable();
StackTraceElement ste = t.getStackTrace()[1];

System.out.println(ste.getMethodName() + " called me.");
System.out.println("File Name :"+ste.getFileName());
System.out.println("Line Number :"+ste.getLineNumber());
}

}

Leave a Comment