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

7 Comments:

Post a Comment | Home | Inference: my personal blog