Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++?

like image 576
DuduAlul Avatar asked Aug 12 '10 13:08

DuduAlul


1 Answers

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
}
like image 134
jjnguy Avatar answered Oct 02 '22 10:10

jjnguy