AspectJ(2)Language Introduction
AspectJ(2)Language Introduction
Chapter 2. The AspectJ Language
2.1 The Anatomy of an Aspect
An Example Aspect
...snip...
Join Points and Pointcuts
After reading and study withincode demo, I begin to understand this key words. withincode, that means that be in this method of that class in this example.
PointTests.java:
package com.sillycat.easyaspectj;
import junit.framework.TestCase;
public class PointTests extends TestCase {
public static void main(String args[]) {
junit.swingui.TestRunner.run(PointTests.class);
}
public void testPointChange() {
Point sample = new Point(1, 1);
assertFalse(sample.isDirty());
sample.setX(5);
assertTrue(sample.isDirty());
sample.save();
assertFalse(sample.isDirty());
sample.setY(2);
assertFalse(sample.isDirty());
sample.save();
assertFalse(sample.isDirty());
}
}
My aspectj class AspectPoint.aj:
package com.sillycat.easyaspectj;
public aspect AspectPoint {
private boolean Point.isDirty = false;
public void Point.makeDirty() {
isDirty = true;
}
public boolean Point.isDirty() {
return isDirty;
}
public void Point.save() {
isDirty = false;
// add code to save point
}
pointcut fieldChanged(Point changed) :
set( private double Point.*) &&
target(changed) &&
!withincode( Point.new(..)) &&
withincode( void Point.setX(..));
after(Point changed ) : fieldChanged(changed) {
System.out.println("Make Dirty");
changed.makeDirty();
}
}
Point.java class is as follow:
public class Point {
private double x;
private double y;
private boolean isDirty = false;
Point(double x, double y) {
this.x = x;
this.y = y;
}
public void setX(double x) {
this.x = x;
isDirty = true;
}
public void setY(double y) {
this.y = y;
isDirty = true;
}
public void setPolarCoordinates(double theta, double r) {
x = r * Math.cos(theta);
y = r * Math.sin(theta);
isDirty = true;
}
...snip..
Some Example Pointcuts
When a particular method body executes: execution(void Point.setX(int))
When a method is called: call(void Point.setX(int))
When an exception handler executes: handler(ArrayOutOfBoundsException)
When the object currently executing is of type SomeType: this(SomeType)
When the target object is of type SomeType: target(SomeType)
When the executing code belongs to class MyClass: within(MyClass)
call VS. execution
Pointcut composition
Pointcut Parameters
Example: HandleLiveness
2.2. Advice
The around advice runs instead of the join point. The original action associated with the join point can be invoked through the special proceed call:
public void sayHello(String message){
System.out.println(message);
}
public static void main(String[] args) {
HelloWorld h = new HelloWorld();
h.sayHello(" study the aspectJ!");
h.sayHello(" study the spring roo!");
h.sayHello(" study the mw3!");
}
pointcut hello(HelloWorld h1, String hello):
target(h1) && args(hello) && (call (void say*(String)));
void around(HelloWorld h1,String hello): hello(h1, hello