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,918
  • 9
  • 54
  • 67

4 Answers4

4

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

AlexR
  • 114,158
  • 16
  • 130
  • 208
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,353
  • 6
  • 49
  • 70
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
  • 463
  • 1
  • 6
  • 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,579
  • 2
  • 29
  • 42