Consider the following Java class:
class Point { private int x, y; Point(int x, int y) { this.x = x; this.y = y; } void setX(int x) { this.x = x; } void setY(int y) { this.y = y; } int getX() { return x; } int getY() { return y; } }
In order to get an intuitive understanding of AspectJ's join points and pointcuts, let's go back to some of the basic principles of Java. Consider the following a method declaration in class Point:
void setX(int x) { this.x = x; }
This piece of program says that when method named
setX
with an int
argument
called on an object of type Point
, then the method
body { this.x = x; }
is executed. Similarly, the
constructor of the class states that when an object of type
Point
is instantiated through a constructor with
two int
arguments, then the constructor body
{ this.x = x; this.y = y; }
is executed.
One pattern that emerges from these descriptions is
When something happens, then something gets executed.
In object-oriented programs, there are several kinds of "things that happen" that are determined by the language. We call these the join points of Java. Join points consist of things like method calls, method executions, object instantiations, constructor executions, field references and handler executions. (See the AspectJ Quick Reference for a complete listing.)
Pointcuts pick out these join points. For example, the pointcut
pointcut setter(): target(Point) && (call(void setX(int)) || call(void setY(int)));
picks out each call to setX(int)
or
setY(int)
when called on an instance of
Point
. Here's another example:
pointcut ioHandler(): within(MyClass) && handler(IOException);
This pointcut picks out each the join point when exceptions of type
IOException
are handled inside the code defined by
class MyClass
.
Pointcut definitions consist of a left-hand side and a right-hand side, separated by a colon. The left-hand side consists of the pointcut name and the pointcut parameters (i.e. the data available when the events happen). The right-hand side consists of the pointcut itself.
Here are examples of pointcuts picking out
execution(void Point.setX(int))
call(void Point.setX(int))
handler(ArrayOutOfBoundsException)
this
) is of type
SomeType
this(SomeType)
SomeType
target(SomeType)
MyClass
within(MyClass)
Test
's no-argument main
method
cflow(call(void Test.main()))
Pointcuts compose through the operations or
("||
"), and
("&&
") and not
("!
").
It is possible to use wildcards. So
execution(* *(..))
call(* set(..))
means (1) the execution of any method regardless of return or
parameter types, and (2) the call to any method named
set
regardless of return or parameter types
-- in case of overloading there may be more than one such
set
method; this pointcut picks out calls to
all of them.
You can select elements based on types. For example,
execution(int *())
call(* setY(long))
call(* Point.setY(int))
call(*.new(int, int))
means (1) the execution of any method with no parameters that
returns an int
, (2) the call to any
setY
method that takes a
long
as an argument, regardless of return
type or declaring type, (3) the call to any of
Point
's setY
methods that
take an int
as an argument, regardless of
return type, and (4) the call to any classes' constructor, so
long as it takes exactly two int
s as
arguments.
You can compose pointcuts. For example,
target(Point) && call(int *())
call(* *(..)) && (within(Line) || within(Point))
within(*) && execution(*.new(int))
!this(Point) && call(int *(..))
means (1) any call to an int
method with no
arguments on an instance of Point
,
regardless of its name, (2) any call to any method where the
call is made from the code in Point
's or
Line
's type declaration, (3) the execution of
any constructor taking exactly one int
argument, regardless of where the call is made from, and
(4) any method call to an int
method when
the executing object is any type except Point
.
You can select methods and constructors based on their modifiers and on negations of modifiers. For example, you can say:
call(public * *(..))
execution(!static * *(..))
execution(public !static * *(..))
which means (1) any call to a public method, (2) any execution of a non-static method, and (3) any execution of a public, non-static method.
Pointcuts can also deal with interfaces. For example, given the interface
interface MyInterface { ... }
the pointcut call(* MyInterface.*(..))
picks
out any call to a method in MyInterface
's
signature -- that is, any method defined by
MyInterface
or inherited by one of its a
supertypes.
When methods and constructors run, there are two interesting times associated with them. That is when they are called, and when they actually execute.
AspectJ exposes these times as call and execution join points,
respectively, and allows them to be picked out specifically by
call
and execution
pointcuts.
So what's the difference between these join points? Well, there are a number of differences:
Firstly, the lexical pointcut declarations
within
and withincode
match
differently. At a call join point, the enclosing code is that of
the call site. This means that call(void m())
&& withincode(void m())
will only capture
directly recursive calls, for example. At an execution join point,
however, the program is already executing the method, so the
enclosing code is the method itself: execution(void m())
&& withincode(void m())
is the same as
execution(void m())
.
Secondly, the call join point does not capture super calls to non-static methods. This is because such super calls are different in Java, since they don't behave via dynamic dispatch like other calls to non-static methods.
The rule of thumb is that if you want to pick a join point that
runs when an actual piece of code runs (as is often the case for
tracing), use execution
, but if you want to pick
one that runs when a particular signature is
called (as is often the case for production aspects), use
call
.
Pointcuts are put together with the operators and (spelled
&&
), or (spelled ||
),
and not (spelled !
). This allows the creation
of very powerful pointcuts from the simple building blocks of
primitive pointcuts. This composition can be somewhat confusing
when used with primitive pointcuts like cflow
and cflowbelow
. Here's an example:
cflow(
picks out
each join point in the control flow of the join points picked out
by P
)P
. So, pictorially:
P --------------------- \ \ cflow of P \
What does cflow(
pick out? Well, it
picks out each join point that is in both the control flow of
P
) &&
cflow(Q
)P
and in the control flow of
Q
. So...
P --------------------- \ \ cflow of P \ \ \ Q -------------\------- \ \ \ cflow of Q \ cflow(P) && cflow(Q) \ \
Note that P
and
Q
might not have any join points in
common... but their control flows might have join points in common.
But what does cflow(
mean? Well, it
means the control flow of those join points that are both picked
out by P
&& Q
)P
and picked out by
Q
.
P && Q ------------------- \ \ cflow of (P && Q) \
and if there are no join points that are both
picked by P
and picked out by
Q
, then there's no chance that there are
any join points in the control flow of
(
.
P
&&
Q
)
Here's some code that expresses this.
public class Test { public static void main(String[] args) { foo(); } static void foo() { goo(); } static void goo() { System.out.println("hi"); } } aspect A { pointcut fooPC(): execution(void Test.foo()); pointcut gooPC(): execution(void Test.goo()); pointcut printPC(): call(void java.io.PrintStream.println(String)); before(): cflow(fooPC()) && cflow(gooPC()) && printPC() && !within(A) { System.out.println("should occur"); } before(): cflow(fooPC() && gooPC()) && printPC() && !within(A) { System.out.println("should not occur"); } }
The !within(
pointcut above is required to avoid the A
)printPC
pointcut applying to the System.out.println
call in the advice body. If this was not present a recursive call
would result as the pointcut would apply to its own advice.
(See the section called “Infinite loops” for more details.)
Consider again the first pointcut definition in this chapter:
pointcut setter(): target(Point) && (call(void setX(int)) || call(void setY(int)));
As we've seen, this pointcut picks out each call to
setX(int)
or setY(int)
methods where the target is an instance of
Point
. The pointcut is given the name
setters
and no parameters on the left-hand
side. An empty parameter list means that none of the context from
the join points is published from this pointcut. But consider
another version of version of this pointcut definition:
pointcut setter(Point p): target(p) && (call(void setX(int)) || call(void setY(int)));
This version picks out exactly the same join points. But in this
version, the pointcut has one parameter of type
Point
. This means that any advice that uses this
pointcut has access to a Point
from each join
point picked out by the pointcut. Inside the pointcut definition
this Point
is named p
is
available, and according to the right-hand side of the definition,
that Point p
comes from the
target
of each matched join point.
Here's another example that illustrates the flexible mechanism for defining pointcut parameters:
pointcut testEquality(Point p): target(Point) && args(p) && call(boolean equals(Object));
This pointcut also has a parameter of type
Point
. Similar to the
setters
pointcut, this means that anyone using
this pointcut has access to a Point
from each
join point. But in this case, looking at the right-hand side we
find that the object named in the parameters is not the target
Point
object that receives the call; it's the
argument (also of type Point
) passed to the
equals
method when some other
Point
is the target. If we wanted access to both
Point
s, then the pointcut definition that would
expose target Point p1
and argument
Point p2
would be
pointcut testEquality(Point p1, Point p2): target(p1) && args(p2) && call(boolean equals(Object));
Let's look at another variation of the setters
pointcut:
pointcut setter(Point p, int newval): target(p) && args(newval) && (call(void setX(int)) || call(void setY(int)));
In this case, a Point
object and an
int
value are exposed by the named
pointcut. Looking at the the right-hand side of the definition, we
find that the Point
object is the target object,
and the int
value is the called method's
argument.
The use of pointcut parameters is relatively flexible. The most important rule is that all the pointcut parameters must be bound at every join point picked out by the pointcut. So, for example, the following pointcut definition will result in a compilation error:
pointcut badPointcut(Point p1, Point p2): (target(p1) && call(void setX(int))) || (target(p2) && call(void setY(int)));
because p1
is only bound when calling
setX
, and p2
is only bound
when calling setY
, but the pointcut picks out
all of these join points and tries to bind both
p1
and p2
.
The example below consists of two object classes (plus an exception
class) and one aspect. Handle objects delegate their public,
non-static operations to their Partner
objects. The aspect HandleLiveness
ensures that,
before the delegations, the partner exists and is alive, or else it
throws an exception.
class Handle { Partner partner = new Partner(); public void foo() { partner.foo(); } public void bar(int x) { partner.bar(x); } public static void main(String[] args) { Handle h1 = new Handle(); h1.foo(); h1.bar(2); } } class Partner { boolean isAlive() { return true; } void foo() { System.out.println("foo"); } void bar(int x) { System.out.println("bar " + x); } } aspect HandleLiveness { before(Handle handle): target(handle) && call(public * *(..)) { if ( handle.partner == null || !handle.partner.isAlive() ) { throw new DeadPartnerException(); } } } class DeadPartnerException extends RuntimeException {}
During compilation, AspectJ processes pointcuts in order to try and optimize matching performance. Examining code and determining if each join point matches (statically or dynamically) a given pointcut is a costly process. (A dynamic match means the match cannot be fully determined from static analysis and a test will be placed in the code to determine if there is an actual match when the code is running). On first encountering a pointcut declaration, AspectJ will rewrite it into an optimal form for the matching process. What does this mean? Basically pointcuts are rewritten in DNF (Disjunctive Normal Form) and the components of the pointcut are sorted such that those components that are cheaper to evaluate are checked first. This means users do not have to worry about understanding the performance of various pointcut designators and may supply them in any order in their pointcut declarations.
However, AspectJ can only work with what it is told, and for optimal performance of matching the user should think about what they are trying to achieve and narrow the search space for matches as much as they can in the definition. Basically there are three kinds of pointcut designator: kinded, scoping and context:
A well written pointcut should try and include at least the first two types (kinded and scoping), whilst the contextual designators may be included if wishing to match based on join point context, or bind that context for use in the advice. Supplying either just a kinded designator or just a contextual designator will work but could affect weaving performance (time and memory used) due to all the extra processing and analysis. Scoping designators are very fast to match, they can very quickly dismiss groups of join points that should not be further processed - that is why a good pointcut should always include one if possible.