实现说明
整个示例围绕类 AuditTrail和函数 record、main、helper组织。
使用要点
main的演示流程是record、helper——跑一遍文件,这条流程从头到尾可见。
常见问题
「StackWalker 惰性定位调用方」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
主签名形如 private static void record(String event)
核心语句
.filter(frame -> frame.getDeclaringClass() != AuditTrail.class)
.findFirst()
.map(frame -> frame.getDeclaringClass().getSimpleName()
+ "#" + frame.getMethodName())
.orElse("(unknown)"));
代码示例
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");
}
}