Lazy stack inspection with StackWalker
Inspect stack frames lazily with StackWalker instead of materializing a complete stack trace.
Code Comparison
✕ Materialized stack trace
StackTraceElement caller = Thread.currentThread()
.getStackTrace()[2];
String callerClass = caller.getClassName();
✓ Java 9+
String callerClass = StackWalker.getInstance()
.walk(frames -> frames.skip(1)
.findFirst()
.orElseThrow()
.getClassName());
See a problem with this code? Let us know.
Why the modern way wins
Lazy traversal
Visits only the frames the operation needs.
Stream-friendly
Filtering and selection use standard stream operations.
Configurable
Options support class references and hidden or reflective frames.
Old Approach
Thread.getStackTrace()
Modern Approach
StackWalker
Since JDK
9
Difficulty
Intermediate
JDK Support
Lazy stack inspection with StackWalker
Available
Widely available since JDK 9 (September 2017)
How it works
StackWalker exposes a lazy stream of stack frames and configurable access to retained class references. Code can stop once it finds the needed frame rather than allocating an entire stack-trace array.
Related Documentation
Proof