什么时候可以在Java 9中使用StackWalker.getCallerClass()方法?
Java9为延迟访问提供了一种有效的堆栈遍历方式,使用StackWalkerAPI过滤堆栈跟踪。StackWalker的对象可以允许我们遍历和访问堆栈。此类包含一些有用的方法,例如walk(),forEach()和getCallerClass()。
getCallerClass()方法返回的类调用调用此方法的方法。为了掌握调用类的实例,我们在获取StackWalker实例时需要RETAIN_CLASS_REFERENCE。RETAIN_CLASS_REFERENCE保留StackWalker遍历的所有类的实例。
语法
public Class<?> getCallerClass()
示例
import java.lang.StackWalker.Option;
public class StackWalkerTest {
public static void main(String args[]) {
StackWalkerTest1.test1();
}
}
class StackWalkerTest1 {
protected static void test1() {
StackWalkerTest2.test2();
}
}
class StackWalkerTest2 {
protected static void test2() {
System.out.println(StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE).getCallerClass());
}
}输出结果
class StackWalkerTest1
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志