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
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.