How do I know which class called a method?
class A {
B b = new B();
public void methodA() {
Class callerClass = b.getCallerCalss(); // it should be 'A' class
}
}
class B {
public Class getCallerCalss() {
//... ???
return clazz;
}
}
This is easily done with
Thread.currentThread().getStackTrace().[3]is used because[0]is the element forThread.currentThread(),[1]is forgetCallerClass,[2]is fordoSomething, and finally,[3]ismain. If you putdoSomethingin another class, you’ll see it returns the correct class.