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?

2 Answers 2

1

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

4
  • Could you add some explanation?
    – Undo
    Dec 2, 2013 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 2, 2013 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 3, 2013 at 4: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 3, 2013 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.