10

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?

Kara
  • 6,115
  • 16
  • 50
  • 57
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453

1 Answers1

8

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

Simone Gianni
  • 11,426
  • 40
  • 49
  • So 'o' will be the caller of my method for sure? Even if the server method is called from static code? – Jérôme Verstrynge Sep 08 '11 at 17:42
  • 1
    @JVerstry: The [documentation](http://www.eclipse.org/aspectj/doc/released/progguide/semantics-pointcuts.html) states that the `this` pointcut "Will not match any join points from static contexts." – Mike Daniels Sep 08 '11 at 17:49
  • I think documentation means "in case of a static method execution, there is no this, so it can't be captured using this()". – Simone Gianni Sep 08 '11 at 17:55
  • JVersity, have you found a way of getting the static part, in case thisJoinPoint.getThis() returns null you should be able to use thisJoinPointStaticPart – Simone Gianni Sep 09 '11 at 13:50
  • @SimoneGianni what is `thisEnclosingJoinPointStaticPart`? Where is it defined? – OrangeDog Oct 24 '16 at 15:17
  • thisJoinPoint and thisEnclosingJoinPointStaticPart are automatically available inside an advice, see here http://www.eclipse.org/aspectj/doc/next/progguide/language-thisJoinPoint.html – Simone Gianni Oct 28 '16 at 08:46