Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 816
Jérôme Verstrynge Avatar asked Sep 08 '11 17:09

Jérôme Verstrynge


1 Answers

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

like image 152
Simone Gianni Avatar answered Nov 10 '22 01:11

Simone Gianni