我正在研究一个方面方面,需要知道它从哪里调用.目前我正在使用
new Throwable().getStackTrace();
Run Code Online (Sandbox Code Playgroud)
访问此信息,但每个方面需要几百微秒才能运行.
我看过SecurityManager,但似乎只能得到我的类名.
还有其他我错过的选择吗?
更新
JMH基准测试结果在我对@ apangin答案的评论中提到:
Benchmark Mode Cnt Score Error Units
MyBenchmark.javalangaccess13i avgt 100 2025.865 ± 8.133 ns/op
MyBenchmark.javalangaccess2i avgt 100 2648.598 ± 24.369 ns/op
MyBenchmark.throwable1 avgt 100 12706.978 ± 84.651 ns/op
Run Code Online (Sandbox Code Playgroud)
基准代码:
@Benchmark
public StackTraceElement[] throwable1() {
return new Throwable().getStackTrace();
}
@SuppressWarnings("restriction")
@Benchmark
public static StackTraceElement javalangaccess2i() {
Exception e = new Exception();
return sun.misc.SharedSecrets.getJavaLangAccess().getStackTraceElement(e, 2);
}
@SuppressWarnings("restriction")
@Benchmark
public static StackTraceElement javalangaccess13i() {
Exception e = new Exception();
return sun.misc.SharedSecrets.getJavaLangAccess().getStackTraceElement(e, 13);
}
Run Code Online (Sandbox Code Playgroud)
在戴尔XPS13 9343(i5-5200U …