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

后端 未结 12 1162
鱼传尺愫
鱼传尺愫 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

    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
    

    According to the Javadocs:

    The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.

    A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

    You will have to experiment to determine which index you want (probably stackTraceElements[1] or [2]).

提交回复
热议问题