How to find the calling class in Java?   #


/** * This snippet shows how to write a method whoCalledMe() to find the calling * method that can be used in any method. * * @author java4learners * */ public class Caller { /** * Who Called the method * * @return */ public static 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 */ public static void main(String[] args) { System.out.println(Caller.whoCalledMe()); } } }

Loading Please Wait...