Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
RE: [aspectj-users] A newbie writes



Robbie,

The get and set pointcuts have the same context as the call pointcut in the
"this" binds to the object accessing the field and "target" to the object
owning the field rather than the field itself. So in the following example
we can use before advice with set and args pointcuts to inspect changes to
the "string" field and after returning advice with the get pointcut to
inspect fields accesses. Remember target will not bind to static fields and
using this will exclude static accessor methods.

public class Test {

      public String string = "old";

}

public class Main {

      public void test () {
            Test t = new Test();
            String s = t.string;
            t.string = "new";
      }

      public static void main (String[] args) {
            new Main().test();
      }
}

public aspect Aspect {

      before (Object a, Object o, String s) : set(String Test.*) && args(s)
&& this(a) && target(o) {
            System.out.println(a + "->" + o + ": "+ s);
      }

      after (Object a, Object o) returning(String s) : get(String Test.*)
&& this(a) && target(o) {
            System.out.println(a + "<-" + o + ": " + s);
      }
}

Running the program produces the following output:

      test.pointcut.get.Test@126b249->test.pointcut.get.Test@126b249: old
      test.pointcut.get.Main@182f0db<-test.pointcut.get.Test@126b249: old
      test.pointcut.get.Main@182f0db->test.pointcut.get.Test@126b249: new

To obtain the value of a field before it is set is a little tricky as it
requires reflection or direct field access within the advice.

Matthew Webster
AOSD Project
Java Technology Centre, MP146
IBM Hursley Park, Winchester,  SO21 2JN, England
Telephone: +44 196 2816139 (external) 246139 (internal)
Email: Matthew Webster/UK/IBM @ IBMGB, matthew_webster@xxxxxxxxxx
http://w3.hursley.ibm.com/~websterm/



Back to the top