Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to display all stack frames of the current thread in Java 9?
Stack Walking API can provide a flexible mechanism to traverse and extract information from call stacks that allow us to filter and access frames in a lazy manner. StackWalker class is an entry point to Stack Walking API. The stack trace is a representation of a call stack at a certain point of time in which each element represents a method invocation. It contains all invocations from the start of a thread until the point it’s generated.
In the below example, we can print/display all stack frames of the current thread by using StackWalker API.
Example
import java.lang.StackWalker.StackFrame;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
public class StackWalkerTest {
public static void main(String args[]) throws Exception {
Method test1Method = Helper1.class.<strong>getDeclaredMethod</strong>("test1", (Class<!--?-->[])null);
test1Method.invoke(null, (Object[]) null);
}
}
<strong>// Helper1 class
</strong>class Helper1 {
protected static void test1() {
Helper2.test2();
}
}
<strong>// Helper2 class</strong>
class Helper2 {
protected static void test2() {
<strong>List<StackFrame></strong> stack = <strong>StackWalker.getInstance().walk</strong>((s) -> s.<strong>collect</strong>(Collectors.toList()));
for(<strong>StackFrame </strong>frame : stack) {
System.out.println(frame.<strong>getClassName()</strong> + " " + frame.<strong>getLineNumber()</strong> + " " + frame.<strong>getMethodName()</strong>);
}
}
}
Output
<strong>Helper2 23 test2 Helper1 16 test1 StackWalkerTest 9 main</strong>
Advertisements
