This snippet shows how to write a method whoCalledMe() which would be used to find the calling method. This example leverages the fact that the JVM maintains a stack wherein, it adds the method names as they are invoked, so the top method in the stack is one that would have called the current one.
<!--break-->
package com.livrona.snippets.util;
/**
* This snippet shows how to write a method whoCalledMe() to find the calling
* method that can be used in any method.
*
* @author java4learners
*
*/
publicclass Caller {
/**
* Who Called the method
*
* @return
*/
publicstatic String whoCalledMe() {
String retVal ="";
// The constructor for Throwable has a native function that fills the
// stack trace.
java.lang.StackTraceElement[] trace = (new Throwable()).getStackTrace();
// Once you have the trace you can pick out information you need.
if (trace.length >=2) {
retVal = trace[1].getClassName() +"." + trace[1].getMethodName()
+"()";
}
return retVal;
}
/**
* Main method
*
* @param args
*/
publicstaticvoid main(String[] args) {
System.out.println(Caller.whoCalledMe());
}
}