Print all stack frames of the current thread

suggest change

The following prints all stack frames of the current thread:

package test;

import java.lang.StackWalker.StackFrame;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

public class StackWalkerExample {
    public static void main(String[] args) throws ReflectiveOperationException {
        Method fooMethod = FooHelper.class.getDeclaredMethod("foo");
        fooMethod.invoke(null);
    }
}

class FooHelper {
    protected static void foo() {
        BarHelper.bar();
    }
}

class BarHelper {
    protected static void bar() {
        List<StackFrame> stack = StackWalker.getInstance().walk(stream -> stream.collect(Collectors.toList()));
        for (StackFrame frame : stack) {
            System.out.println(frame.getClassName() + " " + frame.getLineNumber() + " " + frame.getMethodName());
        }
    }
}
test.BarHelper 26 bar
test.FooHelper 19 foo
test.StackWalkerExample 13 main

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents