How can I get the current stack trace in Java?

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

    Getting stacktrace:

    StackTraceElement[] ste = Thread.currentThread().getStackTrace();
    

    Printing stacktrace (JAVA 8+):

    Arrays.asList(ste).forEach(System.out::println);
    

    Printing stacktrage (JAVA 7):

    StringBuilder sb = new StringBuilder();
    
    for (StackTraceElement st : ste) {
        sb.append(st.toString() + System.lineSeparator());
    }
    System.out.println(sb);
    

提交回复
热议问题