Breaking News
Home / Java / Java FAQ / How to find the calling class in Java?

How to find the calling class in Java?

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(….)



Check Also

When is OCAJP Java certification going live?

After completing the BETA phase of testing last year, the Oracle’s new OCAJP Java certification, …

Leave a Reply