How do I figure out what class called my method without passing any variable to that method? let's say we have something like this:
Class A{}
Class B{}
Class C{
public void method1{}
System.out.print("Class A or B called me");
}
let's say an instance of Class A calls an instance of class C and the same for class B. When class A calls class C method1 method, I want it to print something like "Class A called me", and when class B called it to print "Class B called me".
There's no really easy way to do this, because normally a method doesn't and shouldn't need to care from where it is called. If you write your method so that it behaves differently depending on where it was called from, then your program is quickly going to turn into an incomprehensible mess.
However, here's an example:
public class Prut {
public static void main(String[] args) {
example();
}
public static void example() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement element = stackTrace[2];
System.out.println("I was called by a method named: " + element.getMethodName());
System.out.println("That method is in class: " + element.getClassName());
}
}
You can use Thread.currentThread().getStackTrace()
It returns an array of [StackTraceElements][1]
which represents the current stack trace of a program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With