Java – Getting the caller to a Spring AOP Proxy


I'm searching for a way of developing a MethodInterceptor which prints the caller class.

Is there any way of getting the caller object into the method interceptor?

Best Solution

This might work, declare an exception and then use it to get a look at the stack at the time when your method is intercepted:

Throwable t = new Throwable();
StackTraceElement[] elements = t.getStackTrace();

String calleeMethod = elements[0].getMethodName();
String callerMethodName = elements[1].getMethodName();
String callerClassName = elements[1].getClassName();

System.out.println("CallerClassName=" + callerClassName + " , Caller method name: " + callerMethodName);
System.out.println("Callee method name: " + calleeMethod);