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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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
    
}


Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
methods ,aspectj ,java

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}