Is there a way to dump a stack trace without throwing an exception in java?

I am thinking of creating a debug tool for my Java application.

I am wondering if it is possible to get a stack trace, just like Exception.printStackTrace() but without actually throwing an exception?

My goal is to, in any given method, dump a stack to see who the method caller is.


您还可以尝试使用Thread.getAllStackTraces()为所有活动的线程获取堆栈跟踪的映射。


是的,只需使用

Thread.dumpStack()

If you want the trace for just the current thread (rather than all the threads in the system, as Ram's suggestion does), do:

Thread.currentThread().getStackTrace()

To find the caller, do:

private String getCallingMethodName() {
    StackTraceElement callingFrame = Thread.currentThread().getStackTrace()[4];
    return callingFrame.getMethodName();
}

And call that method from within the method that needs to know who its caller is. However, a word of warning: the index of the calling frame within the list could vary according to the JVM! It all depends on how many layers of calls there are within getStackTrace before you hit the point where the trace is generated. A more robust solution would be to get the trace, and iterate over it looking for the frame for getCallingMethodName, then take two steps further up to find the true caller.

链接地址: http://www.djcxy.com/p/82438.html

上一篇: 我如何重新抛出Javascript中的异常,但保留堆栈?

下一篇: 有没有办法转储堆栈跟踪而不会在java中引发异常?