Search code examples
javajavascriptpythonprogramming-languagesclassloader

Java or any other language: Which method/class invoked mine?


I would like to write a code internal to my method that print which method/class has invoked it.

(My assumption is that I can't change anything but my method..)

How about other programming languages?

EDIT: Thanks guys, how about JavaScript? python? C++?


Solution

  • This is specific to Java.

    You can use Thread.currentThread().getStackTrace(). This will return an array of StackTraceElements.

    The 2nd element in the array will be the calling method.

    Example:

    public void methodThatPrintsCaller() {
        StackTraceElement elem = Thread.currentThread.getStackTrace()[2];
        System.out.println(elem);
    
        // rest of you code
    }