A short post to clarify something that was a little mysterious from the documentation.
AspectJ around advice typically looks something like:
pointcut myPointCut( ) : execution(void my.package.myClass.myMethod()); void around(): myPointCut() { // do some stuff proceed(); // call the advised method // do some other stuff }
What if I want to call other methods or use fields from myClass in the advice? There are a few moving parts here:
pointcut myPointCut( ) : execution(void my.package.myClass.myMethod()); void around(my.package.myClass myClass): target(myClass) && myPointCut() { myClass.method1(); // do some stuff proceed(myClass); // call the advised method myClass.publicField = null; // do some other stuff }
To break it down:
- Add a parameter to around() with the type of the advised class.
- Use the AspectJ target() method to populate that parameter.
- Use the parameter value within the advice however you like. But note that you’re limited to public accessible methods and members – despite what you might think, the advice isnot within the lexical scope of the advised class.
- Add the parameter value as the first parameter to proceed().
This example is for an advised method with no parameters. If the method has parameters:
pointcut myPointCut( ) : execution(void my.package.myClass.myMethod(my.package.ParamClass param)); void around(my.package.myClass myClass, my.package.ParamClass param): target(myClass) && args(param) && myPointCut() { myClass.method1(); // do some stuff proceed(myClass, param); // call the advised method myClass.publicField = null; // do some other stuff }