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

前端 未结 10 1402
庸人自扰
庸人自扰 2020-12-04 07:37

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()

10条回答
  •  情深已故
    2020-12-04 08:20

    Java 9 introduced the StackWalker and supporting classes for walking the stack.

    Here are a few snippets from the Javadoc:

    The walk method opens a sequential stream of StackFrames for the current thread and then applies the given function to walk the StackFrame stream. The stream reports stack frame elements in order, from the top most frame that represents the execution point at which the stack was generated to the bottom most frame. The StackFrame stream is closed when the walk method returns. If an attempt is made to reuse the closed stream, IllegalStateException will be thrown.

    ...

    1. To snapshot the top 10 stack frames of the current thread,

      List stack = StackWalker.getInstance().walk(s ->
       s.limit(10).collect(Collectors.toList()));
      

提交回复
热议问题