java - 如何使用堆栈跟踪或反射找到方法的调用者?

标签 java stack-trace

我需要找到方法的调用者。是否可以使用堆栈跟踪或反射?

最佳答案

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

根据 Javadocs:

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

StackTraceElement 具有 getClassName()getFileName()getLineNumber()getMethodName ().

您必须进行试验才能确定您想要哪个索引 (可能是 stackTraceElements[1][2])。

关于java - 如何使用堆栈跟踪或反射找到方法的调用者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57080630/

相关文章:

java - 来自 GWT 的原始 Java 堆栈跟踪?

gcc - 使用 GCC 编译器的 ARM 核心堆栈回溯(当有 MSP 到 PSP 切换时)

java - 使用 Map 填充 Java 对象

java - 在 Apache Beam 中从 GCS 读取文件

java - C++ 相当于 Java 的 this.getClass().getSimpleName();

java - 为什么有些堆栈跟踪在 java 中没有行号

java - NoClassDefFoundError 是否总是由 ClassNotFoundException 引起?

java - 如何获取调用者(或调用者的调用者,或更深入的调用堆栈)实例 ID - my.package.MyClass@3e7bfc04

java - 将 json 对象消费到一个以 json 数组作为哈希集的类中

java - 无法从 jms activemq 队列中删除消息