[update] jdk StackWalker使用修正

This commit is contained in:
maxf
2025-08-11 09:29:08 +08:00
parent a4be814442
commit d9a548ba44
4 changed files with 126 additions and 3 deletions

View File

@@ -15,6 +15,15 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>

View File

@@ -1,6 +1,7 @@
package top.yexuejc.demo;
import java.lang.StackWalker;
import java.util.stream.Collectors;
public class StackWalkerDemo {
public static void main(String[] args) {
@@ -22,11 +23,17 @@ public class StackWalkerDemo {
.walk(stackFrameStream ->
stackFrameStream
.filter(frame -> frame.getClassName().contains("StackWalkerDemo"))
.peek(frame -> System.out.println(frame.getClassName() + "." + frame.getMethodName()))
);
.map(frame -> frame.getClassName() + "." + frame.getMethodName())
.collect(Collectors.toList())
).forEach(System.out::println);
System.out.println("\n=== 调用者信息 ===");
// 获取直接调用者信息
StackWalker.getInstance().walk(stackStream -> stackStream.skip(1).findFirst()).ifPresent(caller -> System.out.println("调用者: " + caller.getClassName() + "." + caller.getMethodName()));
StackWalker.getInstance()
.walk(stackStream ->
stackStream.skip(1).findFirst()
).ifPresent(caller ->
System.out.println("调用者: " + caller.getClassName() + "." + caller.getMethodName())
);
}
}

View File

@@ -0,0 +1,16 @@
package top.yexuejc.demo;
import org.junit.jupiter.api.Test;
/**
* @author maxiaofeng
* @date 2025/8/11 9:20
*/
class StackWalkerDemoTest {
@Test
void methodA() {
StackWalkerDemo.methodA();
}
}