/* Illustrating per-target aspects. We use seperate instances of an aspect to monitor how many times a method has been called, and prevents it from being called more than 3 times. (This is rather like what you can do with concurrent programming - but there the threads would have to be synchronized, but here, everything is done asynchronously, at least in appearance.) */ interface fun { void f(int x); } class myfun implements fun { public void f(int x) { System.out.println(x+" is fun"); } } class yourfun implements fun { public void f(int x) { System.out.println(x+" is no fun"); } } // The following creates an aspect for each target object of the specified // pointcut. That is, for each object of type fun there will be a separate // "monitoring" aspect: // "fun+" means fun or any subclass of fun: aspect tracker pertarget(execution(fun+.new(..))) { private int counter = 0; before() : call(* fun+.f(int)) { if (++counter > 3) throw new Error("can't call too many times!"); } } public class targets { public static void main(String[] args) { myfun f1 = new myfun(); yourfun f2 = new yourfun(); f1.f(1); f1.f(2); f2.f(1); f2.f(2); f1.f(3); f2.f(3); f1.f(4); f2.f(4); } // main } /* output of this program is: 1 is fun 2 is fun 1 is no fun 2 is no fun 3 is fun 3 is no fun Exception in thread "main" java.lang.Error: can't call too many times! Without the "pertarget" declaration, the output would be: 1 is fun 2 is fun 1 is no fun Exception in thread "main" java.lang.Error: can't call too many times! because the counter variable would be common for all objects. */