You can do this by inspecting the stack upon the method call to your code. Check out Thread.getStackTrace() and use the current thread as returned by
Thread.currentThread()
You can work your way back up the stack trace array and determine the chain of callers. Note the caveat in the documentation however:
Some virtual machines may, under some circumstances, omit one or more
stack frames from the stack trace. In the extreme case, a virtual
machine that has no stack trace information concerning this thread is
permitted to return a zero-length array from this method.
If you need to find out who called you for a subset of your classes, I would change the classes such that they implement some Caller
/Callee
interfaces and implement method signatures thus:
public void doSomething(..., Caller caller);
where your calling class implements Caller
. That way you're enforcing some relatively type-safe method calls and parameter passing.