1

I have class X and in it there is a static method called doStuff() and I have several other classes with methods that call to doStuff() for some reason. Is there a way for example to have a print method in doStuff() that prints from which methods and classes it is called ?

nyxz
  • 6,440
  • 8
  • 51
  • 66

4 Answers4

4

Yes: new Throwable().getStackTrace() returns array of StackTraceElement. Index number 1 is your caller.

AlexR
  • 111,884
  • 15
  • 126
  • 200
2
/**
 * <li> 0 dumpThreads
 * <li> 1 getStackTrace
 * <li> 2 getCallingMethodName
 * <li> 3 [calling method]
 * 
 * @return
 */
private String getCallingMethodName() {
    return Thread.currentThread().getStackTrace()[3].getMethodName();
}
A4L
  • 17,081
  • 6
  • 47
  • 64
1

You can get the caller class using:

package test;

class TestCaller {
    public static void meth() {
        System.out.println("Called by class: " + sun.reflect.Reflection.getCallerClass(2));
    }
}

public class Main {
    public static void main(String[] args) {
        TestCaller.meth();
    }
}

Output: "Called by class: class test.Main"

rmist
  • 441
  • 1
  • 7
  • 15
0

You don't need to force an Exception in order to do this. Check this similar question:

Is there a way to dump a stack trace without throwing an exception in java?

Community
  • 1
  • 1
everton
  • 7,223
  • 2
  • 27
  • 41