How do I know which class called a method?
class A {
B b = new B();
public void methodA() {
Class callerClass = b.getCallerCalss(); // it should b
You can get the class name of the caller class by fetching the second element of the stack trace:
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
System.out.println(stackTrace[1].getClassName());
The getClassName method of the StackTraceElement class returns with a String
so you won't get a Class
object unfortunately.