How can I get the current stack trace in Java?

前端 未结 21 3235
耶瑟儿~
耶瑟儿~ 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:23

    Thread.currentThread().getStackTrace();
    

    is available since JDK1.5.

    For an older version, you can redirect exception.printStackTrace() to a StringWriter() :

    StringWriter sw = new StringWriter();
    new Throwable("").printStackTrace(new PrintWriter(sw));
    String stackTrace = sw.toString();
    

提交回复
热议问题