StackWalker Inspects Caller Frames

Walk the stack lazily for audit logs: filter frames to the nearest non-self caller, or read the direct caller class with RETAIN_CLASS_REFERENCE.

JavaData Integrity

Code

snippet
import java.util.StackWalker;

public class AuditTrail {

    private static final StackWalker CLASS_ONLY =
            StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);

    private static void record(String event) {
        // getCallerClass grabs the immediate caller in one line: it needs RETAIN_CLASS_REFERENCE
        System.out.println(event + " <- " + CLASS_ONLY.getCallerClass().getSimpleName());

        // walk is a lazy stream: the filter stops at the first non-self frame instead of scanning the whole stack
        String nearest = CLASS_ONLY.walk(frames -> frames
                .filter(frame -> frame.getDeclaringClass() != AuditTrail.class)
                .findFirst()
                .map(frame -> frame.getDeclaringClass().getSimpleName()
                        + "#" + frame.getMethodName())
                .orElse("(unknown)"));
        System.out.println(event + " nearest non-self: " + nearest);
    }

    public static void main(String[] args) {
        record("checkout");
        helper();
    }

    static void helper() {
        record("cache-warm");
    }
}

How it works

Count the class AuditTrail and the functions record, main and helper as the entire surface area of StackWalker Inspects Caller Frames.

Putting it to use

Entry signature: private static void record(String event)

Running the file executes main, which drives record and helper in order.

Core lines

.filter(frame -> frame.getDeclaringClass() != AuditTrail.class)
.findFirst()
.map(frame -> frame.getDeclaringClass().getSimpleName()
+ "#" + frame.getMethodName())
.orElse("(unknown)"));

Interactive Tools for This Topic

FAQ

How do you run StackWalker Inspects Caller Frames?
Nothing to install first — run the file and the program does the rest.