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:
main()
|- Foo()
|- Bar()
|- MyFunction()
|- getStackTrace()
|- captureJavaThreadStack(...)
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()
called getStackTrace()
, which means that MyFunction()
will always be above getStackTrace()
, and whatever called MyFunction()
will be above it.
You can use the getClassName()
method on the StackTraceElement
class 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With