2

I have an application which redirect System.out for example;

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

I want to be able to determine which class is sending the call to print to stdout? I think this is not possible, but cannot fully conclude unless SO say so.

Bitmap
  • 12,035
  • 15
  • 62
  • 89

4 Answers4

2

Get the stacktrace and find the class name from the currect index.

StackTraceElement[] trace = Thread.currentThread().getStackTrace();
Prince John Wesley
  • 60,780
  • 12
  • 83
  • 92
  • 1
    In this case it is not particularly easy to determine the correct index in the stack trace and `Thread.currentThread().getStackTrace()` is probably better than `new Exception().getStackTrace()`. – jarnbjo Aug 30 '12 at 11:36
  • @jarnbjo: +1. one stack down the trace. – Prince John Wesley Aug 30 '12 at 11:38
1

You could throw an exception, and examine the stack trace. Obviously not great for production code.

Noel M
  • 15,312
  • 7
  • 37
  • 45
1

If you have a recent version of HotSpot or OpenJDK you can use Reflection.getCallerClass(2 or 3) This is more efficient than generating a full stack trace but not portable.

Otherwise, the most efficient way to get the stack trace is

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

This avoid creating an Exception or Throwable.

Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106
0

There are a number of ways: SecurityManager might be the best. Check this post especially the second answer: How do I find the caller of a method using stacktrace or reflection?

Community
  • 1
  • 1
JTMon
  • 3,161
  • 21
  • 24