Module java.base
Package java.lang

Class StackWalker

java.lang.Object
java.lang.StackWalker

public final classStackWalkerextendsObject
A stack walker.

Thewalk method opens a sequential stream ofStackFrames for the current thread and then applies the given function to walk theStackFrame stream. The stream reports stack frame elements in order, from the top most frame that represents the execution point at which the stack was generated to the bottom most frame. TheStackFrame stream is closed when thewalk method returns. If an attempt is made to reuse the closed stream,IllegalStateException will be thrown.

Stack walker options configure the stack frame information obtained by aStackWalker. By default, the class name and method information are collected but not theClass reference. The method information can be dropped via theDROP_METHOD_INFO option. TheClass object can be retained for access via theRETAIN_CLASS_REFERENCE option. Stack frames of the reflection API and implementation classes arehidden by default.

StackWalker is thread-safe. Multiple threads can share a singleStackWalker object to traverse its own stack. A permission check is performed when aStackWalker is created, according to the options it requests. No further permission check is done at stack walking time.

API Note:
Examples

1. To find the first caller filtering out a known list of implementation class:

    StackWalker walker = StackWalker.getInstance(Set.of(Option.DROP_METHOD_INFO, Option.RETAIN_CLASS_REFERENCE));    Optional<Class<?>> callerClass = walker.walk(s ->            s.map(StackFrame::getDeclaringClass)             .filter(Predicate.not(implClasses::contains))             .findFirst());

2. To snapshot the top 10 stack frames of the current thread,

    List<StackFrame> stack = StackWalker.getInstance().walk(s -> s.limit(10).toList());
Unless otherwise noted, passing anull argument to a constructor or method in thisStackWalker class will cause aNullPointerException to be thrown.

Since:
9