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.
There's a method of observing the stacktrace
StackTraceElement[] elements = Thread.currentThread().getStackTrace()
Javadoc
The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.
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.
Try Throwable.getStackTrace()
.
Create a new Throwable
.. you don't have to throw it :).
untested:
Throwable t = new Throwable();
StackTraceElement[] es = t.getStackTrace();
// Not sure if es[0] would contain the caller, or es[1]. My guess is es[1].
System.out.println( es[0].getClass() + " or " + es[1].getClass() + " called me.");
Obviously if you're creating some function (getCaller()
) then you'll have to go another level up in the stack trace.