How can I get the current stack trace in Java?

前端 未结 21 3302
耶瑟儿~
耶瑟儿~ 2020-11-21 23:49

How do I get the current stack trace in Java, like how in .NET you can do Environment.StackTrace?

I found Thread.dumpStack() but it is not what I want -

21条回答
  •  星月不相逢
    2020-11-22 00:24

    To get the stack trace of all threads you can either use the jstack utility, JConsole or send a kill -quit signal (on a Posix operating system).

    However, if you want to do this programmatically you could try using ThreadMXBean:

    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] infos = bean.dumpAllThreads(true, true);
    
    for (ThreadInfo info : infos) {
      StackTraceElement[] elems = info.getStackTrace();
      // Print out elements, etc.
    }
    

    As mentioned, if you only want the stack trace of the current thread it's a lot easier - Just use Thread.currentThread().getStackTrace();

提交回复
热议问题