Find the Calling Class


Here is a simple snippet to find out the calling Java Class.

Class.forName(new Throwable().getStackTrace()[2].getClassName()));

Basically it create a exception object (Throwable in this case), then get the Stack Trace associated witht he thread so far. Since the stack trace if FIFO, the Calling classes would have called this current class and would have been positioned at the 2 place in the stack. So get the class name for 2nd element by calling getClassName() and finally wraping all this by the outer Class.forName(....)

 

 

 

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.

Back to top