Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to know the caller class name?

Tags:

java

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
}

}
like image 639
Santosh Avatar asked Dec 03 '22 06:12

Santosh


1 Answers

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

like image 195
Polynomial Avatar answered Dec 05 '22 19:12

Polynomial