2

I don't know if this is possible, but I am trying to write a pointcut which would match any method that returns an object implementing a specific interface.

Given the following:

public class User implements Auditable{
   private int id;

   private String name;

   public String getName(){
      return name;
   }
}

and the interface Auditable:

public interface Auditable{
   public String getName();
}

And some random class:

public class RandomClass{
    public User getNewUser(){
       User u = new User();
       return u;
    }
}

How can I write an "AfterReturning" pointcut that would catch any method called getNew* that implements Auditable?

The following works:

pointcut auditablePointcut(): call(public * *.getNew*(..))

however, that will match any returning type. The following does not work:

pointcut auditablePointcut(): call(public Auditable *.getNew*(..))

I presume I could write it using an if(), but that seems a little kludgy (I haven't tried it yet). Or is there a more elegant manner?

Eric B.
  • 23,425
  • 50
  • 169
  • 316

2 Answers2

1

after () returning (Audible au) : call(public * *.getNew*(..))

aepurniet
  • 1,719
  • 16
  • 24
  • Could you add some explanation? – Undo Dec 02 '13 at 19:34
  • `after () returning (Audible au)` will only match pointcuts that return an `Audible`. `au` will be available as a variable within the body of the advice. – aepurniet Dec 02 '13 at 19:38
  • Why is that different than call(public Auditable *.getNew*(..))? Don't they both point to methods that return Auditable? Or does this match the exact method signature while your proposed solution match against the actual object being returned? – Eric B. Dec 03 '13 at 04:20
  • `call(public Audible...)` matches the signature, and doesnt capture the return object (unless that is done else where in the pointcut). return(Audible) should match and capture the returned object, but the pointcut will be applied to all `getNew*` methods, since there is no filtering on signature (except the name). – aepurniet Dec 03 '13 at 18:57
0

I'm not sure about pointcut, but you can check return type of the method in aspects like this:

MethodSignature signature = (MethodSignature)joinPoint.getSignature();
signature.getReturnType(); // method return type
WelcomeTo
  • 811
  • 8
  • 11