27 February 2006

How to obtain caller method (jdk 1.4+)

Sometimes you want to know which class/method called your function. Starting with Java 1.4, java.lang.StackTraceElement provides an easy way to accomplish this. Here is how

StackTraceElement[] telements = new Exception().getStackTrace();
String callerClass = telements[1].getClassName();
String callerMethod = telements[1].getMethodName();

The array's 0th item is your method and 1st item is the method that called your method.

GetJava Download Button

No comments: