本文介绍了如何使用堆栈跟踪或反射找到方法的调用者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

根据 Javadoc:

According to the Javadocs:

数组的最后一个元素代表栈底,它是序列中最近的方法调用.

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

您必须通过试验来确定您想要的索引(可能是 stackTraceElements[1][2]).

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

这篇关于如何使用堆栈跟踪或反射找到方法的调用者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 19:57