aspectj 以get和set切入点的形式提供了类属性上的任何访问和修改的监视。
捕获何时访问对象的属性
get(FieldPattern)
Picks out each field reference join point whose signature matches FieldPattern. [Note that references to constant fields (static final fields bound to a constant string object or primitive value) are not join points, since Java requires them to be inlined.]
说明
get切入点触发直接在其中,而不是访问器方法的调用上
不能捕获对静态属性的访问,也不适合常量
捕获访问的字段值
after( Formals ) returning [ ( Formal ) ]
捕获何时修改对象的字段
set(FieldPattern)
Picks out each field set join point whose signature matches FieldPattern. [Note that the initializations of constant fields (static final fields where the initializer is a constant string object or primitive value) are not join points, since Java requires their references to be inlined.]
说明
不能捕获静态字段的修改
在修改字段是捕获它的值
args结合set使用
demo
将上面四个场景融合在了一起
package aspectj;
public aspect HelloWorld {
//指定fieldPattern
pointcut getPointcut():get(int MyClass.b);
pointcut setPointcut():set(int MyClass.b);
pointcut setPointcutValue(int value):set(int MyClass.b) && args(value);
//捕获何时访问对象的属性
before(): getPointcut()
{
System.out.println("get field");
System.out.println(thisJoinPoint.getSignature());
System.out.println(thisJoinPoint.getSourceLocation());
}
//捕获访问的字段值
after() returning(int value): getPointcut() {
System.out.println("get field value " + value);
System.out.println(thisJoinPoint.getSignature());
System.out.println(thisJoinPoint.getSourceLocation());
}
//捕获何时修改对象的属性
before(): setPointcut() {
System.out.println("set field");
System.out.println(thisJoinPoint.getSignature());
System.out.println(thisJoinPoint.getSourceLocation());
}
//捕获何时修改对象的值
before(int value): setPointcutValue(value) {
System.out.println("set field with value " + value);
System.out.println(thisJoinPoint.getSignature());
System.out.println(thisJoinPoint.getSourceLocation());
}
}
package aspectj;
public class MyClass {
private int b;
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.b=3;
System.out.println(myClass.b);
}
}
输出
set field
int aspectj.MyClass.b
MyClass.java:8
set field with value 3
int aspectj.MyClass.b
MyClass.java:8
get field
int aspectj.MyClass.b
MyClass.java:9
get field value 3
int aspectj.MyClass.b
MyClass.java:9
3
很好理解
备注
FieldPattern =
[ModifiersPattern] TypePattern [TypePattern . ] IdPattern
refer
https://eclipse.org/aspectj/doc/released/progguide/semantics-pointcuts.html
https://eclipse.org/aspectj/doc/released/progguide/semantics-advice.html
《aspectj cookbook》