Even a chimp can write code

Sunday, October 03, 2004

How to determine the calling class in Java

I once tried a dirty hack that involved parsing the stack trace of an exception instance, but this would return the calling class name much efficiently:




String callingClassName =
sun.reflect.Reflection.getCallerClass(2).getName();



The getCallerClass method takes an int argument where a value of 0 (zero) returns sun.reflect.Reflection, 1 returns the class of the currently executing method and every increment looks up the call stack.

If you are bothered by the prospect of using a sun.* API, you may (write a utility class to) sub-class the SecurityManager and use its protected native Class[] getClassContext() method which returns the call stack. The element at index 0 is the class of the currently executing method, the element at 1 is the caller and so on up the stack.

Email this | Bookmark this

4 Comments:

  • Alternatively, on JDK 1.4+ you could just say "new Thread().getStackTrace()[1].getClassName()".

    By Anonymous Anonymous, at October 3, 2004 at 2:06 PM  

  • I'd check that getStackTrace actually returns an array with some elements, or you could end up throwing ArrayOutOfBoundsException unexpectedly.

    -- Tom Hawtin

    By Anonymous Anonymous, at October 3, 2004 at 11:53 PM  

  • Here's the best way to do it:

    Throwable stack = new Throwable();
    stack.fillInStackTrace();
    stack.getStackTrace(1).getClassName();

    You can also get calling method, line #, etc. Much more reliable.

    By Anonymous Anonymous, at September 7, 2005 at 12:29 PM  

  • What if the calling method is on an abstract class and I want to know the name of the concrete subclass used for the call?

    Malcolm

    By Anonymous Anonymous, at July 16, 2006 at 10:38 PM  

Post a Comment | Home | Inference: my personal blog