Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

AspectJ: Using Advised Class Fields

DZone's Guide to

AspectJ: Using Advised Class Fields

A few quick code snippets to explain how to call other methods or use fields in AspectJ.

· Java Zone
Free Resource

Learn how to stop testing everything every sprint and only test the code you’ve changed. Brought to you by Parasoft.

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:

  1. Add a parameter to around() with the type of the advised class.
  2. Use the AspectJ target() method to populate that parameter.
  3. 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.
  4. 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
    
}


Get the top tips for Java developers and best practices to overcome common challenges. Brought to you by Parasoft.

Topics:
methods ,aspectj ,java

Published at DZone with permission of Jaime Metcher, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}