How do I find the caller of a method using stacktrace or reflection?

后端 未结 12 1178
鱼传尺愫
鱼传尺愫 2020-11-21 13:26

I need to find the caller of a method. Is it possible using stacktrace or reflection?

12条回答
  •  遥遥无期
    2020-11-21 13:57

    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.

提交回复
热议问题