How can I get the current stack trace in Java?

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

    You can use jstack utility if you want to check the current call stack of your process.

    Usage:
        jstack [-l] <pid>
            (to connect to running process)
        jstack -F [-m] [-l] <pid>
            (to connect to a hung process)
        jstack [-m] [-l] <executable> <core>
            (to connect to a core file)
        jstack [-m] [-l] [server_id@]<remote server IP or hostname>
            (to connect to a remote debug server)
    
    Options:
        -F  to force a thread dump. Use when jstack <pid> does not respond (process is hung)
        -m  to print both java and native frames (mixed mode)
        -l  long listing. Prints additional information about locks
        -h or -help to print this help message
    
    0 讨论(0)
  • 2020-11-22 00:37
    Thread.currentThread().getStackTrace();
    

    is fine if you don't care what the first element of the stack is.

    new Throwable().getStackTrace();
    

    will have a defined position for your current method, if that matters.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题