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
This is easily done with Thread.currentThread().getStackTrace().
public static void main(String[] args) {
doSomething();
}
private static void doSomething() {
System.out.println(getCallerClass());
}
private static Class> getCallerClass() {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
String clazzName = stackTrace[3].getClassName();
try {
return Class.forName(clazzName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
[3] is used because [0] is the element for Thread.currentThread(), [1] is for getCallerClass, [2] is for doSomething, and finally, [3] is main. If you put doSomething in another class, you'll see it returns the correct class.