Tim Milstead
Tim Milstead

Reputation: 41

AspectJ Pointcut On All Executions of a Method Without Specific Annotations

How do I write a pointcut that triggers when a method, e.g. all setters on MyClass, is executed but that method is missing some specific annotations e.g. @Ann1 and @Ann2

Upvotes: 0

Views: 137

Answers (1)

Andy Clement
Andy Clement

Reputation: 2560

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@interface Ann1 {}

@Retention(RetentionPolicy.RUNTIME)
@interface Ann2 {}

public class Code {
  public void setFoo() {}
  @Ann1 public void setBar() {}
  @Ann2 public void setBoo() {}
  @Ann1 @Ann2 public void setFar() {}
}

aspect X {
  before(): execution(!@Ann1 !@Ann2 * set*(..)) {}
}

Now compile it:

ajc -1.5 -showWeaveInfo Code.java

Join point 'method-execution(void Code.setFoo())' in Type 'Code' (Code.java:10) advised by before advice from 'X' (Code.java:17)

See that only setFoo() is advised. A pointcut like this:

before(): execution(!@Ann1 * set*(..)) || execution(!@Ann2 * set*(..)) {}

would match where either @Ann1 or @Ann2 is missing (so the first 3 setters).

Upvotes: 1

Related Questions