Is it possible to retrieve the object instance performing a method call with AspectJ?

Let's imagine the following aspect:

 aspect FaultHandler {

   pointcut services(Server s): target(s) && call(public * *(..));

   before(Server s): services(s) {
     // How to retrieve the calling object instance?
     if (s.disabled) ...;
   }

 }

The pointcut captures all calls to public methods of Server and runs the before advice just before any of these are called.

Is it possible to retrieve the object instance performing the call to the public Server method in the before advice? If yes, how?

Upvotes: 10

Views: 6227

Answers (1)

Simone Gianni
Simone Gianni

Reputation: 11662

you can use the this() pointcut :

pointcut services(Server s, Object o) : target(s) && this(o) && call....

Obviously, you can use a specific type instead of Object if you need to scope it.

EDIT

You can also use the thisJoinPoint variable :

Object o = thisJoinPoint.getThis();

While using thisJoinPoint often incur in a small performance penalty compared to using specific pointcuts, it can be used in case the caller is a static class.

In that case, there is no "this", so this(o) may fail to match, and thisJoinPoint.getThis() return null.

However, using :

Class c = thisEnclosingJoinPointStaticPart.getSignature().getDeclaringType();

Will tell you the class that contains the static method. Exploring more fields on signature can also give you the method name etc..

Upvotes: 8

Related Questions