2

例如,我有一个重定向的应用程序System.out

  System.setOut(new PrintStream(System.out){
    @Override
    public void print(String string)
    {
      //TODO: find out who sent the print before processing string
    }
  });

我希望能够确定哪个类将打印调用发送到标准输出?我认为这是不可能的,但除非SO这样说,否则不能完全得出结论。

4

4 回答 4

2

获取堆栈跟踪并从当前索引中找到类名。

StackTraceElement[] trace = Thread.currentThread().getStackTrace();
于 2012-08-30T11:24:52.243 回答
1

您可以抛出异常,并检查堆栈跟踪。显然不适合生产代码。

于 2012-08-30T11:19:41.010 回答
1

如果您有最新版本的 HotSpot 或 OpenJDK,您可以使用Reflection.getCallerClass(2 or 3)这比生成完整堆栈跟踪更有效,但不可移植。

否则,获取堆栈跟踪的最有效方法是

StackTraceElement[] stes = Thread.currentThread.getStackTrace();

这样可以避免创建 Exception 或 Throwable。

于 2012-08-30T11:27:43.613 回答
0

有很多方法:SecurityManager 可能是最好的。检查这篇文章,尤其是第二个答案:如何使用堆栈跟踪或反射找到方法的调用者?

于 2012-08-30T11:25:04.583 回答