Lets say I have a method classA.methodA() and its calling classB.methodB(). Now, inside the classB.methodB(), is there any way to know that its being called by classA (without passing any explicit info). I know this info is there in Java Runtime. My question is how to get the the class name of callee method ?
to make it more obvious
ClassA{
methodA(){
ClassB b = new ClassB();
b.methodB();
}
}
ClassB{
methodB(){
// Code to find that its being called by ClassA
}
}
You can use
Thread.currentThread().getStackTrace()to get a stack trace, then iterate through it to find which method is above yours in the stack.For example (totally made up stack here), you might have a stack like this:
Starting from the bottom, you iterate up until you hit the
getStackTrace()method. You then know that the calling method is two methods up from that position, i.e.MyFunction()calledgetStackTrace(), which means thatMyFunction()will always be abovegetStackTrace(), and whatever calledMyFunction()will be above it.You can use the
getClassName()method on theStackTraceElementclass to pull out the class name from the selected stack trace element.Docs:
http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#getStackTrace%28%29
http://docs.oracle.com/javase/6/docs/api/java/lang/StackTraceElement.html