Recipe8.3.Capturing When an Object s Field Is Modified


Recipe 8.3. Capturing When an Object's Field Is Modified

Problem

You want to capture when an object's field is modified.

Solution

Use the set(Signature) pointcut. The syntax of the set(Signature) pointcut is:

pointcut <pointcut name>(<any values to be picked up>) :              set(<optional modifier> <type> <class>.<field>);

Discussion

The set(Signature) pointcut has four key characteristics:

  1. The set(Signature) pointcut triggers when a field is modified.

  2. The set(Signature) pointcut cannot capture modification of static fields although it is perfectly legal within the syntax of AspectJ to define a pointcut in this way.

  3. The Signature must resolve to an attribute of a particular class.

  4. The Signature can include wildcard characters to select a range of join points on different attributes.

Example 8-4 shows the set(Signature) pointcut capturing join points encountered whenever the String MyClass.name attribute is modified.

Example 8-4. Using the set(Signature) pointcut to capture join points when an attribute is modified
public aspect SetRecipe  {    /*        Specifies calling advice whenever an attribute         matching the following rules is modified:            Type: String        Class Name: MyClass        Attribute Name: name    */    pointcut setNamePointcut( ) : set(String MyClass.name);    // Advice declaration    before( ) : setNamePointcut( ) && !within(SetRecipe +)    {       System.out.println(          "------------------- Aspect Advice Logic --------------------");       System.out.println(          "In the advice picked by " + "setNamePointcut( )");       System.out.println(          "Signature: "             + thisJoinPoint.getStaticPart( ).getSignature( ));       System.out.println(          "Source Line: "             + thisJoinPoint.getStaticPart( ).getSourceLocation( ));       System.out.println(          "------------------------------------------------------------");    } }

Figure 8-2 shows how the set(Signature) pointcut is applied to a simple class.

Figure 8-2. How the set(Signature) pointcut is applied


See Also

Recipe 4.1 shows some of the wildcard variations that can be used in a Signature; Chapter 13 describes the different types of advice available in AspectJ; the within(TypePattern) pointcut is described in Recipe 9.1; the NOT(!) operator is described in Recipe 12.4.



AspectJ Cookbook
Aspectj Cookbook
ISBN: 0596006543
EAN: 2147483647
Year: 2006
Pages: 203
Authors: Russ Miles

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net