At times (chain-of-responsibilty pattern, debugging etc), it is very handy to know in a method being called, which method invoked it. For example You may have an inheritance class hierarchy , which has got a method overridden by its subclasses. Let us look at some sample code to see how this can be achieved using StackTraceElement and Throwable :
The base caller class:
Code:public class CallerBase { public void methodC1() { new Callee().doSomething(); } public static void main(String[] args) { CallerBase caller = new CallerBase(); caller.methodC1(); caller = new CallerSub(); caller.methodC1(); } }
The subclass of the caller class:
finally the important part of the code which determines who invoked it:Code:public class CallerSub extends CallerBase { public void methodC1() { new Callee().doSomething(); } }
If you run the class CallerBase then the output is:Code:public class Callee { public void doSomething() { Throwable t = new Throwable(); StackTraceElement[] elements = t.getStackTrace(); String calleeMethod = elements[0].getMethodName(); String callerMethodName = elements[1].getMethodName(); String callerClassName = elements[1].getClassName(); System.out.println("CallerClassName=" + callerClassName + " , Caller method name: " + callerMethodName); System.out.println("Callee method name: " + calleeMethod); } }
CallerClassName=CallerBase , Caller method name: methodC1
Callee method name: doSomething
CallerClassName=CallerSub , Caller method name: methodC1
Callee method name: doSomething
-- from the author of the book "Java/J2EE Job Interview Companion" at http://www.lulu.com/java-success


Reply With Quote


Bookmarks