views:

435

answers:

2

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?

A: 

You could do something crude with generating a stack trace and inspecting it, but that is ugly

Chris Kimpton
A: 

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);

bwobbones