APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.lang

public final Class StackWalker

extends Object
Class Inheritance
Imports
jdk.internal.reflect.CallerSensitive, java.lang.invoke.MethodType, java.util.EnumSet, .Objects, .Set, java.util.function.Consumer, .Function, java.util.stream.Stream, jdk.internal.vm.Continuation, .ContinuationScope

A stack walker.

The walk method opens a sequential stream of StackFrames for the current thread and then applies the given function to walk the StackFrame 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. The StackFrame stream is closed when the walk 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 a StackWalker. By default, the class name and method information are collected but not the Class reference. The method information can be dropped via the DROP_METHOD_INFO option. The Class object can be retained for access via the RETAIN_CLASS_REFERENCE option. Stack frames of the reflection API and implementation classes are hidden by default.

StackWalker is thread-safe. Multiple threads can share a single StackWalker object to traverse its own stack.

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());
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());
List<StackFrame> stack = StackWalker.getInstance().walk(s -> s.limit(10).toList());
Unless otherwise noted, passing a null argument to a constructor or method in this StackWalker class will cause a NullPointerException to be thrown.
Since
9

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static enum
public static enum
StackWalker.Option

Stack walker option to configure the stack frame information obtained by a StackWalker.

public static interface
StackWalker.StackFrame

A StackFrame object represents a method invocation returned by StackWalker.

Field Summary

Modifier and TypeField and Description
private final Continuation
private final ContinuationScope
pack-priv static final EnumSet<StackWalker.Option>
private static final StackWalker
private final int
private final StackWalker.ExtendedOption
private final Set<StackWalker.Option>
pack-priv final boolean

Constructor Summary

AccessConstructor and Description
private
private
StackWalker(EnumSet<StackWalker.Option> options, int estimateDepth)

private
StackWalker(EnumSet<StackWalker.Option> options, int estimateDepth, StackWalker.ExtendedOption extendedOption, ContinuationScope contScope, Continuation continuation)

Method Summary

Modifier and TypeMethod and Description
pack-priv int
public void
forEach(Consumer<? super StackWalker.StackFrame>
an action to be performed on each StackFrame of the stack of the current thread
action
)

Performs the given action on each element of StackFrame stream of the current thread, traversing from the top frame of the stack, which is the method calling this forEach method.

public Class<?>

Returns:

Class object of the caller's caller invoking this method.
getCallerClass
()

Gets the Class object of the caller who invoked the method that invoked getCallerClass.

pack-priv Continuation
pack-priv ContinuationScope
public static StackWalker

Returns:

a StackWalker configured to skip all hidden frames and no class reference is retained.
getInstance
()

Returns a StackWalker instance.

public static StackWalker

Returns:

a StackWalker configured with the given option
getInstance
(StackWalker.Option option)

Returns a StackWalker instance with the given option specifying the stack frame information it can access.

public static StackWalker

Returns:

a StackWalker configured with the given options
getInstance
(Set<StackWalker.Option> options)

Returns a StackWalker instance with the given options specifying the stack frame information it can access.

public static StackWalker

Returns:

a StackWalker configured with the given options
getInstance
(Set<StackWalker.Option> options, int
Estimate number of stack frames to be traversed.
estimateDepth
)

Returns a StackWalker instance with the given options specifying the stack frame information it can access.

pack-priv boolean
pack-priv boolean
pack-priv static StackWalker
pack-priv static StackWalker
pack-priv static StackWalker
pack-priv static StackWalker
newInstance(Set<StackWalker.Option> options, StackWalker.ExtendedOption extendedOption, ContinuationScope contScope, Continuation continuation)

private static EnumSet<StackWalker.Option>
public <
The type of the result of applying the function to the stream of stack frame.
T
>
T

Returns:

the result of applying the function to the stream of stack frame.
walk
(Function<? super Stream<StackWalker.StackFrame>, ? extends T>
a function that takes a stream of stack frames and returns a result.
function
)

Applies the given function to the stream of StackFrames for the current thread, traversing from the top frame of the stack, which is the method calling this walk method.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

continuationback to summary
private final Continuation continuation
contScopeback to summary
private final ContinuationScope contScope
DEFAULT_EMPTY_OPTIONback to summary
pack-priv static final EnumSet<StackWalker.Option> DEFAULT_EMPTY_OPTION
DEFAULT_WALKERback to summary
private static final StackWalker DEFAULT_WALKER
estimateDepthback to summary
private final int estimateDepth
extendedOptionback to summary
private final StackWalker.ExtendedOption extendedOption
optionsback to summary
private final Set<StackWalker.Option> options
retainClassRefback to summary
pack-priv final boolean retainClassRef

Constructor Detail

StackWalkerback to summary
private StackWalker(EnumSet<StackWalker.Option> options)
StackWalkerback to summary
private StackWalker(EnumSet<StackWalker.Option> options, int estimateDepth)
StackWalkerback to summary
private StackWalker(EnumSet<StackWalker.Option> options, int estimateDepth, StackWalker.ExtendedOption extendedOption, ContinuationScope contScope, Continuation continuation)

Method Detail

estimateDepthback to summary
pack-priv int estimateDepth()
forEachback to summary
public void forEach(Consumer<? super StackWalker.StackFrame> action)

Performs the given action on each element of StackFrame stream of the current thread, traversing from the top frame of the stack, which is the method calling this forEach method.

This method is equivalent to calling

walk(s -> { s.forEach(action); return null; });
Parameters
action:Consumer<? super StackWalker.StackFrame>

an action to be performed on each StackFrame of the stack of the current thread

Annotations
@CallerSensitive
getCallerClassback to summary
public Class<?> getCallerClass()

Gets the Class object of the caller who invoked the method that invoked getCallerClass.

This method filters reflection frames, java.lang.invoke.MethodHandle, and hidden frames regardless of the SHOW_REFLECT_FRAMES and SHOW_HIDDEN_FRAMES options this StackWalker has been configured with.

This method should be called when a caller frame is present. If it is called from the bottom most frame on the stack, IllegalCallerException will be thrown.

This method throws UnsupportedOperationException if this StackWalker is not configured with the RETAIN_CLASS_REFERENCE option.

API Note

For example, Util::getResourceBundle loads a resource bundle on behalf of the caller. It invokes getCallerClass to identify the class whose method called Util::getResourceBundle. Then, it obtains the class loader of that class, and uses the class loader to load the resource bundle. The caller class in this example is MyTool.

class Util { private final StackWalker walker = StackWalker.getInstance(Set.of(Option.DROP_METHOD_INFO, Option.RETAIN_CLASS_REFERENCE)); public ResourceBundle getResourceBundle(String bundleName) { Class<?> caller = walker.getCallerClass(); return ResourceBundle.getBundle(bundleName, Locale.getDefault(), caller.getClassLoader()); } } class MyTool { private final Util util = new Util(); private void init() { ResourceBundle rb = util.getResourceBundle("mybundle"); } }
class Util {
    private final StackWalker walker =
        StackWalker.getInstance(Set.of(Option.DROP_METHOD_INFO, Option.RETAIN_CLASS_REFERENCE));
    public ResourceBundle getResourceBundle(String bundleName) {
        Class<?> caller = walker.getCallerClass();
        return ResourceBundle.getBundle(bundleName, Locale.getDefault(), caller.getClassLoader());
    }
}

class MyTool {
    private final Util util = new Util();
    private void init() {
        ResourceBundle rb = util.getResourceBundle("mybundle");
    }
}
An equivalent way to find the caller class using the walk method is as follows (filtering the reflection frames, MethodHandle and hidden frames not shown below):
Optional<Class<?>> caller = walker.walk(s -> s.map(StackFrame::getDeclaringClass) .skip(2) .findFirst());
Optional<Class<?>> caller = walker.walk(s ->
    s.map(StackFrame::getDeclaringClass)
     .skip(2)
     .findFirst());
When the getCallerClass method is called from a method that is the bottom most frame on the stack, for example, static public void main method launched by the java launcher, or a method invoked from a JNI attached thread, IllegalCallerException is thrown.
Returns:Class<?>

Class object of the caller's caller invoking this method.

Annotations
@CallerSensitive
Exceptions
UnsupportedOperationException:
if this StackWalker is not configured with Option.RETAIN_CLASS_REFERENCE.
IllegalCallerException:
if there is no caller frame, i.e. when this getCallerClass method is called from a method which is the last frame on the stack.
getContinuationback to summary
pack-priv Continuation getContinuation()
getContScopeback to summary
pack-priv ContinuationScope getContScope()
getInstanceback to summary
public static StackWalker getInstance()

Returns a StackWalker instance.

This StackWalker is configured to skip all hidden frames and no class reference is retained.

Returns:StackWalker

a StackWalker configured to skip all hidden frames and no class reference is retained.

getInstanceback to summary
public static StackWalker getInstance(StackWalker.Option option)

Returns a StackWalker instance with the given option specifying the stack frame information it can access.

Parameters
option:StackWalker.Option

stack walking option

Returns:StackWalker

a StackWalker configured with the given option

getInstanceback to summary
public static StackWalker getInstance(Set<StackWalker.Option> options)

Returns a StackWalker instance with the given options specifying the stack frame information it can access.

If the given options is empty, this StackWalker is configured to skip all hidden frames and no class reference is retained.

Parameters
options:Set<StackWalker.Option>

stack walking options

Returns:StackWalker

a StackWalker configured with the given options

getInstanceback to summary
public static StackWalker getInstance(Set<StackWalker.Option> options, int estimateDepth)

Returns a StackWalker instance with the given options specifying the stack frame information it can access.

If the given options is empty, this StackWalker is configured to skip all hidden frames and no class reference is retained.

The estimateDepth specifies the estimate number of stack frames this StackWalker will traverse that the StackWalker could use as a hint for the buffer size.

Parameters
options:Set<StackWalker.Option>

stack walking options

estimateDepth:int

Estimate number of stack frames to be traversed.

Returns:StackWalker

a StackWalker configured with the given options

Exceptions
IllegalArgumentException:
if estimateDepth <= 0
hasLocalsOperandsOptionback to summary
pack-priv boolean hasLocalsOperandsOption()
hasOptionback to summary
pack-priv boolean hasOption(StackWalker.Option option)
newInstanceback to summary
pack-priv static StackWalker newInstance(Set<StackWalker.Option> options, StackWalker.ExtendedOption extendedOption)
newInstanceback to summary
pack-priv static StackWalker newInstance(Set<StackWalker.Option> options, ContinuationScope contScope)
newInstanceback to summary
pack-priv static StackWalker newInstance(Set<StackWalker.Option> options, StackWalker.ExtendedOption extendedOption, ContinuationScope contScope)
newInstanceback to summary
pack-priv static StackWalker newInstance(Set<StackWalker.Option> options, StackWalker.ExtendedOption extendedOption, ContinuationScope contScope, Continuation continuation)
toEnumSetback to summary
private static EnumSet<StackWalker.Option> toEnumSet(Set<StackWalker.Option> options)
walkback to summary
public <T> T walk(Function<? super Stream<StackWalker.StackFrame>, ? extends T> function)

Applies the given function to the stream of StackFrames for the current thread, traversing from the top frame of the stack, which is the method calling this walk method.

The StackFrame stream will be closed when this method returns. When a closed Stream<StackFrame> object is reused, IllegalStateException will be thrown.

API Note

For example, to find the first 10 calling frames, first skipping those frames whose declaring class is in package com.foo:

List<StackFrame> frames = StackWalker.getInstance().walk(s -> s.dropWhile(f -> f.getClassName().startsWith("com.foo.")) .limit(10) .toList());
List<StackFrame> frames = StackWalker.getInstance().walk(s ->
        s.dropWhile(f -> f.getClassName().startsWith("com.foo."))
         .limit(10)
         .toList());

This method takes a Function accepting a Stream<StackFrame>, rather than returning a Stream<StackFrame> and allowing the caller to directly manipulate the stream. The Java virtual machine is free to reorganize a thread's control stack, for example, via deoptimization. By taking a Function parameter, this method allows access to stack frames through a stable view of a thread's control stack.

Parallel execution is effectively disabled and stream pipeline execution will only occur on the current thread.

Implementation Note

The implementation stabilizes the stack by anchoring a frame specific to the stack walking and ensures that the stack walking is performed above the anchored frame. When the stream object is closed or being reused, IllegalStateException will be thrown.

Parameters
<T>
The type of the result of applying the function to the stream of stack frame.
function:Function<? super Stream<StackWalker.StackFrame>, ? extends T>

a function that takes a stream of stack frames and returns a result.

Returns:T

the result of applying the function to the stream of stack frame.

Annotations
@CallerSensitive
java.lang back to summary

pack-priv final Enum StackWalker.ExtendedOption

extends Enum<StackWalker.ExtendedOption>
Class Inheritance

Field Summary

Modifier and TypeField and Description
public static final StackWalker.ExtendedOption
LOCALS_AND_OPERANDS

Obtain monitors, locals and operands.

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static StackWalker.ExtendedOption
public static StackWalker.ExtendedOption[]
Inherited from java.lang.Enum:
clonecompareTodescribeConstableequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

Field Detail

LOCALS_AND_OPERANDSback to summary
public static final StackWalker.ExtendedOption LOCALS_AND_OPERANDS

Obtain monitors, locals and operands.

Constructor Detail

ExtendedOptionback to summary
private ExtendedOption()

Method Detail

valueOfback to summary
public static StackWalker.ExtendedOption valueOf(String name)
valuesback to summary
public static StackWalker.ExtendedOption[] values()
java.lang back to summary

public final Enum StackWalker.Option

extends Enum<StackWalker.Option>
Class Inheritance

Stack walker option to configure the stack frame information obtained by a StackWalker.
Since
9

Field Summary

Modifier and TypeField and Description
public static final StackWalker.Option
DROP_METHOD_INFO

Drops the method information from StackFrames walked by this StackWalker.

public static final StackWalker.Option
RETAIN_CLASS_REFERENCE

Retains Class object in StackFrames walked by this StackWalker.

public static final StackWalker.Option
SHOW_HIDDEN_FRAMES

Shows all hidden frames.

public static final StackWalker.Option
SHOW_REFLECT_FRAMES

Shows all reflection frames.

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static StackWalker.Option
public static StackWalker.Option[]
Inherited from java.lang.Enum:
clonecompareTodescribeConstableequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

Field Detail

DROP_METHOD_INFOback to summary
public static final StackWalker.Option DROP_METHOD_INFO

Drops the method information from StackFrames walked by this StackWalker.

A StackWalker configured with this option will drop the method name, the method type, the line number, the bytecode index, the source file name and native method or not.

Since
22
RETAIN_CLASS_REFERENCEback to summary
public static final StackWalker.Option RETAIN_CLASS_REFERENCE

Retains Class object in StackFrames walked by this StackWalker.

A StackWalker configured with this option will support StackWalker#getCallerClass() and StackFrame.getDeclaringClass().

SHOW_HIDDEN_FRAMESback to summary
public static final StackWalker.Option SHOW_HIDDEN_FRAMES

Shows all hidden frames.

A Java Virtual Machine implementation may hide implementation specific frames in addition to reflection frames. A StackWalker with this SHOW_HIDDEN_FRAMES option will show all hidden frames (including reflection frames).

SHOW_REFLECT_FRAMESback to summary
public static final StackWalker.Option SHOW_REFLECT_FRAMES

Shows all reflection frames.

By default, reflection frames are hidden. A StackWalker configured with this SHOW_REFLECT_FRAMES option will show all reflection frames that include java.lang.reflect.Method#invoke and java.lang.reflect.Constructor#newInstance(Object...) and their reflection implementation classes.

The SHOW_HIDDEN_FRAMES option can also be used to show all reflection frames and it will also show other hidden frames that are implementation-specific.

API Note

This option includes the stack frames representing the invocation of Method and Constructor. Any utility methods that are equivalent to calling Method.invoke or Constructor.newInstance such as Class.newInstance are not filtered or controlled by any stack walking option.

Constructor Detail

Optionback to summary
private Option()

Method Detail

valueOfback to summary
public static StackWalker.Option valueOf(String name)
valuesback to summary
public static StackWalker.Option[] values()
java.lang back to summary

public Interface StackWalker.StackFrame

Known Direct Subinterfaces
java.lang.LiveStackFrame
Known Direct Implementers
java.lang.ClassFrameInfo

A StackFrame object represents a method invocation returned by StackWalker.

Stack walker options configure the stack frame information obtained by a StackWalker. If the stack walker is configured with DROP_METHOD_INFO option, method information such as the method name, the line number, the bytecode index, etc will be dropped. If the stack walker is configured with RETAIN_CLASS_REFERENCE option, the Class object will be retained for access.

Since
9
Java Virtual Machine Specification
2.6 Frames

Method Summary

Modifier and TypeMethod and Description
public int

Returns:

the index to the code array of the Code attribute containing the execution point represented by this stack frame, or a negative number if the method is native.
getByteCodeIndex
()

Returns the index to the code array of the Code attribute containing the execution point represented by this stack frame.

public String

Returns:

the binary name of the declaring class of the method represented by this stack frame
getClassName
()

Returns the binary name of the declaring class of the method represented by this stack frame.

public Class<?>

Returns:

the declaring Class for the method represented by this stack frame
getDeclaringClass
()

Returns the declaring Class for the method represented by this stack frame.

public default String

Returns:

the descriptor of the method represented by this stack frame
getDescriptor
()

Returns the descriptor of the method represented by this stack frame as defined by The Java Virtual Machine Specification.

public String

Returns:

the name of the file containing the execution point represented by this stack frame, or null if this information is unavailable.
getFileName
()

Returns the name of the source file containing the execution point represented by this stack frame.

public int

Returns:

the line number of the source line containing the execution point represented by this stack frame, or a negative number if this information is unavailable.
getLineNumber
()

Returns the line number of the source line containing the execution point represented by this stack frame.

public String

Returns:

the name of the method represented by this stack frame
getMethodName
()

Returns the name of the method represented by this stack frame.

public default MethodType

Returns:

the MethodType of the method represented by this stack frame
getMethodType
()

Returns the MethodType representing the parameter types and the return type for the method represented by this stack frame.

public boolean

Returns:

true if the method containing the execution point represented by this stack frame is a native method
isNativeMethod
()

Returns true if the method containing the execution point represented by this stack frame is a native method.

public StackTraceElement

Returns:

StackTraceElement for this stack frame
toStackTraceElement
()

Returns StackTraceElement for this stack frame.

Method Detail

getByteCodeIndexback to summary
public int getByteCodeIndex()

Returns the index to the code array of the Code attribute containing the execution point represented by this stack frame. The code array gives the actual bytes of Java Virtual Machine code that implement the method.

Returns:int

the index to the code array of the Code attribute containing the execution point represented by this stack frame, or a negative number if the method is native.

Exceptions
UnsupportedOperationException:
if the StackWalker is configured with DROP_METHOD_INFO option
Java Virtual Machine Specification
4.7.3 The Code Attribute
getClassNameback to summary
public String getClassName()

Returns the binary name of the declaring class of the method represented by this stack frame.

Returns:String

the binary name of the declaring class of the method represented by this stack frame

Java Language Specification
13.1 The Form of a Binary
getDeclaringClassback to summary
public Class<?> getDeclaringClass()

Returns the declaring Class for the method represented by this stack frame.

Returns:Class<?>

the declaring Class for the method represented by this stack frame

Exceptions
UnsupportedOperationException:
if the StackWalker is configured without RETAIN_CLASS_REFERENCE option
getDescriptorback to summary
public default String getDescriptor()

Returns the descriptor of the method represented by this stack frame as defined by The Java Virtual Machine Specification.

Implementation Specification

The default implementation throws UnsupportedOperationException.

Returns:String

the descriptor of the method represented by this stack frame

Exceptions
UnsupportedOperationException:
if the StackWalker is configured with DROP_METHOD_INFO option
Since
10
Java Virtual Machine Specification
4.3.3 Method Descriptors
See Also
MethodType#fromMethodDescriptorString(String, ClassLoader), MethodType#toMethodDescriptorString()
getFileNameback to summary
public String getFileName()

Returns the name of the source file containing the execution point represented by this stack frame. Generally, this corresponds to the SourceFile attribute of the relevant class file as defined by The Java Virtual Machine Specification. In some systems, the name may refer to some source code unit other than a file, such as an entry in a source repository.

Returns:String

the name of the file containing the execution point represented by this stack frame, or null if this information is unavailable.

Exceptions
UnsupportedOperationException:
if the StackWalker is configured with DROP_METHOD_INFO option
Java Virtual Machine Specification
4.7.10 The SourceFile Attribute
getLineNumberback to summary
public int getLineNumber()

Returns the line number of the source line containing the execution point represented by this stack frame. Generally, this is derived from the LineNumberTable attribute of the relevant class file as defined by The Java Virtual Machine Specification.

Returns:int

the line number of the source line containing the execution point represented by this stack frame, or a negative number if this information is unavailable.

Exceptions
UnsupportedOperationException:
if the StackWalker is configured with DROP_METHOD_INFO option
Java Virtual Machine Specification
4.7.12 The LineNumberTable Attribute
getMethodNameback to summary
public String getMethodName()

Returns the name of the method represented by this stack frame.

Returns:String

the name of the method represented by this stack frame

Exceptions
UnsupportedOperationException:
if the StackWalker is configured with DROP_METHOD_INFO option
getMethodTypeback to summary
public default MethodType getMethodType()

Returns the MethodType representing the parameter types and the return type for the method represented by this stack frame.

Implementation Specification

The default implementation throws UnsupportedOperationException.

Returns:MethodType

the MethodType of the method represented by this stack frame

Exceptions
UnsupportedOperationException:
if the StackWalker is configured with DROP_METHOD_INFO option or without RETAIN_CLASS_REFERENCE option
Since
10
isNativeMethodback to summary
public boolean isNativeMethod()

Returns true if the method containing the execution point represented by this stack frame is a native method.

Returns:boolean

true if the method containing the execution point represented by this stack frame is a native method

Exceptions
UnsupportedOperationException:
if the StackWalker is configured with DROP_METHOD_INFO option
toStackTraceElementback to summary
public StackTraceElement toStackTraceElement()

Returns StackTraceElement for this stack frame.

Returns:StackTraceElement

StackTraceElement for this stack frame

Exceptions
UnsupportedOperationException:
if the StackWalker is configured with DROP_METHOD_INFO option