O'Reilly logo

AspectJ Cookbook by Russ Miles

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.2. Combining Pointcuts Using a Logical AND (&&)

Problem

You want to combine some pointcut declarations, so advice is executed on a join point as long as all conditions within the pointcut declarations evaluate to true.

Solution

Use the && operator. The syntax of the && operator is:

pointcut <pointcut name>(<any values to be picked up>) : 
                        <pointcut declaration> && <pointcut declaration>

Discussion

Example 12-2 shows an example of the && operator combining the logic of two pointcuts into a single pointcut declaration.

Example 12-2. Using the && operator to combine two pointcuts

public aspect LogicalAndRecipe 
{
   /*
           Specifies calling advice whenever a method 
           matching the following rules gets called:
           
           Class Name: MyClass
           Method Name: Any Method
           Method Return Type: Any Return Type
           Method Parameters: Any Parameters
   */
   pointcut callAnyMethodOnMyClass( ) : call(* MyClass.* (..));

   /*
           Specifies calling advice whenever a method 
           matching the following rules gets called:
           
           Class Name: MyClass
           Method Name: bar
           Method Return Type: void
           Method Parameters: None
   */
   pointcut callBarPointcut( ) : call(void MyClass.bar( ));

   /*
           Specifies calling advice whenever a join points is
           encountered that would be picked by both pointcuts
           specified:
           
           Pointcut name: callAnyMethodOnMyClass
           Pointcut name: callBarPointcut
           Method Return Type: void
           Method Parameters: None
   */
   pointcut callIntersectionAnyAndBar( ) : callAnyMethodOnMyClass( )
                           && callBarPointcut( ); // Advice declaration before( ) : callAnyMethodOnMyClass( ) && !within(LogicalAndRecipe ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required