Over a million developers have joined DZone.

AspectJ: Using Advised Class Fields

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

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

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
    
}


Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

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.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}