N01Se
N01Se

Reputation: 1

AspectJ: variable transfer from one matching advice to another

I have two advices matching the same pointcut. They are supposed to be performed one after another. For example:

pointcut som(TargetClass t, CallingClass c): target(t) && this(c) && call(public * TargetClass .*(..) );

before(TargetClass t, CallingClass c): som(t, c) 
{
    System.out.println("Entering: " + thisJoinPoint);
    String identifier = <...>; //Generating unique identifier for a method call
    getMonitor().addRecord(identifier, new Date()); //Sending new record to a custom monitor object
}

after(TargetClass t, CallingClass c): som(t, c) returning
{
    getMonitor().finishRecord(identifier, new Date());
}

This is how I see the logic in general. The problem is how to make a variable created in the "before" advice available in the "after" advice. I do not know ApsectJ well enough to solve this problem.

Upvotes: 0

Views: 54

Answers (1)

kriegaex
kriegaex

Reputation: 67437

This is the corrected version of Stefan's answer (sorry, but I cannot post it as a comment because of the formatted code):

public aspect MyAspect {
    pointcut som(TargetClass t, CallingClass c) :
        target(t) && this(c) && call(public * TargetClass .*(..) );

    Object around(TargetClass t, CallingClass c) : som(t, c) {
        System.out.printf("%s%n  this   = %s%n  target = %s%n", thisJoinPoint, c, t);
        String identifier = UUID.randomUUID().toString();
        getMonitor().addRecord(identifier, new Date());
        Object result = proceed(t, c); 
        getMonitor().finishRecord(identifier, new Date());
        return result;
    }
}
  • around() advices need a return type matching the pointcut or, for lack of better knowledge, Object.
  • The parameter list for proceed() must match the advice's one.
  • Unless the return typ is void, you need to return the result of proceed() (modified or unchanged or even a compeletely different object of the same type replacing the original). You can even skip proceed() if you always want to return another object and stop the original method from being executed altogether.
  • If you want to do something else after proceeding, but before returning the result, you need to buffer the result.

Upvotes: 1

Related Questions