I need to find the caller of a method. Is it possible using stacktrace or reflection?
This method does the same thing but a little more simply and possibly a little more performant and in the event you are using reflection, it skips those frames automatically. The only issue is it may not be present in non-Sun JVMs, although it is included in the runtime classes of JRockit 1.4-->1.6. (Point is, it is not a public class).
sun.reflect.Reflection
/** Returns the class of the method realFramesToSkip
frames up the stack (zero-based), ignoring frames associated
with java.lang.reflect.Method.invoke() and its implementation.
The first frame is that associated with this method, so
getCallerClass(0)
returns the Class object for
sun.reflect.Reflection. Frames associated with
java.lang.reflect.Method.invoke() and its implementation are
completely ignored and do not count toward the number of "real"
frames skipped. */
public static native Class getCallerClass(int realFramesToSkip);
As far as what the realFramesToSkip
value should be, the Sun 1.5 and 1.6 VM versions of java.lang.System
, there is a package protected method called getCallerClass() which calls sun.reflect.Reflection.getCallerClass(3)
, but in my helper utility class I used 4 since there is the added frame of the helper class invocation.