adam bien's blog

Java 9's StackWalker 📎

The Java 9's StackWalker class allows stack walking without instantiating an Exception.

The following unit test:


package com.airhacks;

import java.lang.StackWalker.StackFrame;
import org.junit.Before;
import org.junit.Test;

public class StackWalkerBasicsTest {

    private StackWalker walker;

    @Before
    public void init() {
        this.walker = StackWalker.getInstance();
    }

    @Test
    public void walkTheStack() {
        this.walker.forEach(this::print);
    }

    void print(StackFrame frame) {
        String className = frame.getClassName();
        String methodName = frame.getMethodName();
        int lineNumber = frame.getLineNumber();
        System.out.println(className + "." + methodName + ":" + lineNumber);
    }
}

Writes the following output:


com.airhacks.StackWalkerBasicsTest.walkTheStack:24
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall:50
org.junit.internal.runners.model.ReflectiveCallable.run:12
org.junit.runners.model.FrameworkMethod.invokeExplosively:47
org.junit.internal.runners.statements.InvokeMethod.evaluate:17
org.junit.internal.runners.statements.RunBefores.evaluate:26
org.junit.runners.ParentRunner.runLeaf:325
org.junit.runners.BlockJUnit4ClassRunner.runChild:78
org.junit.runners.BlockJUnit4ClassRunner.runChild:57
org.junit.runners.ParentRunner$3.run:290
org.junit.runners.ParentRunner$1.schedule:71
org.junit.runners.ParentRunner.runChildren:288
org.junit.runners.ParentRunner.access$000:58
org.junit.runners.ParentRunner$2.evaluate:268
org.junit.runners.ParentRunner.run:363
org.apache.maven.surefire.junit4.JUnit4Provider.execute:252
org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet:141
org.apache.maven.surefire.junit4.JUnit4Provider.invoke:112
org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray:189
org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke:165
org.apache.maven.surefire.booter.ProviderFactory.invokeProvider:85
org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess:115
org.apache.maven.surefire.booter.ForkedBooter.main:75    

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.