这就是我想要实现的:如果有一个方法a()调用b()方法,我想知道是谁调用了method b()。
public void a(){
b();//but it is not necessarily in the same class
}
public void b(){
String method = getCallerMethod();//returns 'a'
}现在,可以使用Java在9+中有效地实现这一点。在Java8中,我可以使用Thread.currentThread().getStackTrace()或new Exception().getStackTrace(),但这两种方法都非常慢。我不需要整个堆栈跟踪,我只需要堆栈跟踪中的前一个框架,只需要该框架中的方法名称(可能还需要类名)。
有办法在Java 8中有效地实现这一点吗?
发布于 2020-08-15 00:05:18
start_depth和max_frame_count参数只允许获得堆栈跟踪的选定部分。
这种方法的缺点是它需要一个本机库。
我有一个使用示例的GetStackTrace,它几乎可以满足您的需要:StackFrame.getLocation(depth)方法在给定深度只返回一个堆栈帧。a的所有invoke*字节码,并重写它们以调用方法a_with_caller(String callerMethod),其中callerMethod参数是从正在检测的方法派生的插装时间常数。发布于 2020-08-14 12:35:58
您可以创建am异常并使用fillInStacktrace(),然后printStacktrace()并粘贴结果。
它的效率可能不是很高,但我不明白如果它只用于调试的话,为什么要这样做。
我没有在我的电脑上,所以我没有试着编译它。
try (StringWriter wr = new StringWriter();
PrintWriter pw = new PrintWriter(wr)) {
new Exception().fillInStacktrace().printStacktrace(pw);
try (Scanner sc = new Scanner(wr.toString())) {
int atFound = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.contains("at")) {
atFound++;
}
if (atFound == 2) {
// this should be the caller, first one is this method
}
}
}
} https://stackoverflow.com/questions/63412684
复制相似问题