How can I get the current stack trace in Java?

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

    I used answers from above and added formatting

    public final class DebugUtil {
    
        private static final String SEPARATOR = "\n";
    
        private DebugUtil() {
        }
    
        public static String formatStackTrace(StackTraceElement[] stackTrace) {
            StringBuilder buffer = new StringBuilder();
            for (StackTraceElement element : stackTrace) {
                buffer.append(element).append(SEPARATOR);
            }
            return buffer.toString();
        }
    
        public static String formatCurrentStacktrace() {
            StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
            return formatStackTrace(stackTrace);
        }
    }
    

提交回复
热议问题