The AspectJ Language Introduction The previous chapter, , was a brief overview of the AspectJ language. You should read this chapter to understand AspectJ's syntax and semantics. It covers the same material as the previous chapter, but more completely and in much more detail. We will start out by looking at an example aspect that we'll build out of a pointcut, an introduction, and two pieces of advice. This example aspect will gives us something concrete to talk about. The Anatomy of an Aspect This lesson explains the parts of AspectJ's aspects. By reading this lesson you will have an overview of what's in an aspect and you will be exposed to the new terminology introduced by AspectJ. An Example Aspect Here's an example of an aspect definition in AspectJ: The FaultHandler consists of one variable introduced onto Server (line 03), two methods (lines 05-07 and 09-11), one pointcut (line 13), and two pieces of advice (lines 15-17 and 19-22). This covers the basics of what aspects can contain. In general, aspects consist of an association with other program entities, ordinary variables and methods, pointcuts, introductions, and advice, where advice may be before, after or around advice. The remainder of this lesson focuses on those crosscut-related constructs. Pointcuts AspectJ's pointcuts define collections of events, i.e. interesting points in the execution of a program. These events, or points in the execution, can be method or constructor invocations and executions, handling of exceptions, field assignments and accesses, etc. Take, for example, the pointcut declaration in line 13: This pointcut, named services, picks out those points in the execution of the program when instances of the Server class have their public methods called. The idea behind this pointcut in the FaultHandler aspect is that fault-handling-related behavior must be triggered on the calls to public methods. For example, the server may be unable to proceed with the request because of some fault. The calls of those methods are, therefore, interesting events for this aspect, in the sense that certain fault-related things will happen when these events occur. Part of the context in which the events occur is exposed by the formal parameters of the pointcut. In this case, that consists of objects of type server. That formal parameter is then being used on the right hand side of the declaration in order to identify which events the pointcut refers to. In this case, a pointcut picking out join points where a Server is the target of some operation (target(s)) is being composed (, meaning and) with a pointcut picking out call join points (call(...)). The calls are identified by signatures that can include wild cards. In this case, there are wild cards in the return type position (first *), in the name position (second *) and in the argument list position (..); the only concrete information is given by the qualifier public. What else? Pointcuts define arbitrarily large sets of points in the execution of a program. But they use only a finite number of kinds of points. Those kinds of points correspond to some of the most important concepts in Java. Here is an incomplete list: method invocation, method execution, exception handling, instantiation, constructor execution. Each of these has a specific syntax that you will learn about in other parts of this guide. Advice Advice defines pieces of aspect implementation that execute at join points picked out by a pointcut. For example, the advice in lines 15-17 specifies that the following piece of code is executed when instances of the Server class have their public methods called, as specified by the pointcut services. More specifically, it runs when those calls are made, just before the corresponding methods are executed. The advice in lines 19-22 defines another piece of implementation that is executed on the same pointcut: But this second method executes whenever those operations throw exception of type FaultException. What else? There are two other variations of after advice: upon successful return and upon return, either successful or with an exception. There is also a third kind of advice called around. You will see those in other parts of this guide. Join Points and Pointcuts Consider the following Java class: In order to get an intuitive understanding of AspectJ's pointcuts, let's go back to some of the basic principles of Java. Consider the following a method declaration in class Point: What this piece of program states is that when an object of type Point has a method called setX with an integer as the argument called on it, then the method body { this.x = x; } is executed. Similarly, the constructor given in that class states that when an object of type Point is instantiated through a constructor with two integers as 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 comprised method calls, method executions, instantiations, constructor executions, field references and handler executions. (See the quick reference for complete listing.) Pointcuts pick out these join points. For example, the pointcut describes the calls to setX(int) or setY(int) methods of any instance of Point. Here's another example: This pointcut picks out the join points at which exceptions of type IOException are handled inside the code defined by class MyClass. Pointcuts consist of a left-hand side and a right-hand side, separated by a colon. The left-hand side defines the pointcut name and the pointcut parameters (i.e. the data available when the events happen). The right-hand side defines the events in the pointcut. Pointcuts can then be used to define aspect code in advice, as we will see later. But first let's see what types of events can be captured and how they are described in AspectJ. Designators Here are examples of designators of 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 (i.e. this) 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) when the join point is in the control flow of a call to a Test's no-argument main method cflow(void Test.main()) Designators compose through the operations or ("||"), and ("") and not ("!"). It is possible to use wildcards. So execution(* *(..)) call(* set(..)) means (1) all the executions of methods with any return and parameter types and (2) method calls of set methods with any return and parameter types -- in case of overloading there may be more than one; this designator picks out 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) all executions of methods with no parameters, returning an int (2) the calls of setY methods that take a long as an argument, regardless of their return type or defining type, (3) the calls of class Point's setY methods that take an int as an argument, regardless of the return type, and (4) the calls of all classes' constructors that take two ints as arguments. You can compose designators. For example, target(Point) call(int *()) call(* *(..)) (within(Line) || within(Point)) within(*) execution(*.new(int)) this(*) !this(Point) call(int *(..)) means (1) all calls to methods received by instances of class Point, with no parameters, returning an int, (2) calls to any method where the call is made from the code in Point's or Line's type declaration, (3) executions of constructors of all classes, that take an int as an argument, and (4) all method calls of any method returning an int, from all objects except Point objects to any other objects. 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) all invocation of public methods, (2) all executions of non-static methods, and (3) all signatures of the public, non-static methods. Designators can also deal with interfaces. For example, given the interface the designator call(* MyInterface.*(..)) picks out the call join points for methods defined by the interface MyInterface (or its superinterfaces). call vs. execution 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 times? Well, there are a number of differences: Firstly, the lexical pointcut declarations within and withincode match differently. At a call join point, the enclosing text is that of the call site. This means that This means that call(void m()) within(void m()) will only capture recursive calls, for example. At an execution join point, however, the control is already executing the method. 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, pick an execution, but if you want to pick one that runs when a particular signature is called, pick a call. Pointcut composition 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(P) picks out the join points in the control flow of the join points picked out by P. So, pictorially: P --------------------- \ \ cflow of P \ What does cflow(P) && cflow(Q) pick out? Well, it picks out those join points that are in both the control flow of 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(P && Q) mean? Well, it means the control flow of those join points that are both picked out by P 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. Pointcut Parameters Consider, for example, the first pointcut you've seen here, As we've seen before, the right-hand side of the pointcut picks out the calls to setX(int) or setY(int) methods where the target is any object of type Point. On the left-hand side, the pointcut is given the name "setters" and no parameters. An empty parameter list means that when those events happen no context is immediately available. But consider this other version of the same pointcut: This version picks out exactly the same calls. But in this version, the pointcut has one parameter of type Point. This means that when the events described on the right-hand side happen, a Point object, named by a parameter named "p", is available. According to the right-hand side of the pointcut, that Point object in the pointcut parameters is the object that receives the calls. Here's another example that illustrates the flexible mechanism for defining pointcut parameters: This pointcut also has a parameter of type Point. Similarly to the "setters" pointcut, this means that when the events described on the right-hand side happen, a Point object, named by a parameter named "p", is available. 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 (of type Point) passed to the "equals" method on some other target Point object. If we wanted access to both objects, then the pointcut definition that would define target Point p1 and argument Point p2 would be Let's look at another variation of the "setters" pointcut: In this case, a Point object and an integer value are available when the calls happen. Looking at the events definition on the right-hand side, we find that the Point object is the object receiving the call, and the integer value is the argument of the method . The definition of pointcut parameters is relatively flexible. The most important rule is that when each of those events defined in the right-hand side happen, all the pointcut parameters must be bound to some value. So, for example, the following pointcut definition will result in a compilation error: The right-hand side establishes that this pointcut picks out the call join points consisting of the setX(int) method called on a point object, or the setY(int) method called on a point object. This is fine. The problem is that the parameters definition tries to get access to two point objects. But when setX(int) is called on a point object, there is no other point object to grab! So in that case, the parameter p2 is unbound, and hence, the compilation error. Example: <literal>HandleLiveness</literal> 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. Advice Advice defines pieces of aspect implementation that execute at well-defined points in the execution of the program. Those points can be given either by named pointcuts (like the ones you've seen above) or by anonymous pointcuts. Here is an example of an advice on a named pointcut: And here is exactly the same example, but using an anonymous pointcut: Here are examples of the different advice: This before advice runs just before the execution of the actions associated with the events in the (anonymous) pointcut. This after advice runs just after each join point picked out by the (anonymous) pointcut, regardless of whether it returns normally or throws an exception. This after returning advice runs just after each join point picked out by the (anonymous) pointcut, but only if it returns normally. The return value can be accessed, and is named x here. After the advice runs, the return value is returned. This after throwing advice runs just after each join point picked out by the (anonymous) pointcut, but only when it throws an exception of type Exception. Here the exception value can be accessed with the name e. The advice re-raises the exception after it's done. This around advice traps the execution of the join point; it runs instead of the join point. The original action associated with the join point can be invoked through the special proceed call. Introduction Introduction declarations add whole new elements in the given types, and so change the type hierarchy. Here are examples of introduction declarations: This privately introduces a field named disabled in Server and initializes it to false. Because it is declared private, only code defined in the aspect can access the field. This publicly introduces a method named getX in Point; the method returns an int, it has no arguments, and its body is return x. Because it is defined publically, any code can call it. This publicly introduces a constructor in Point; the constructor has two arguments of type int, and its body is this.x = x; this.y = y; This publicly introduces a field named x of type int in Point; the field is initialized to 0. This declares that the Point class now implements the Comparable interface. Of course, this will be an error unless Point defines the methods of Comparable. This declares that the Point class now extends the GeometricObject class. An aspect can introduce several elements in at the same time. For example, the following declaration publicly introduces both a field and a method into class Point. Note that the identifier "name" in the body of the method is bound to the "name" field in Point, even if the aspect defined another field called "name". One declaration can introduce several elements in several classes as well. For example, publicly introduces three methods, one in Point, another in Line and another in Square. The three methods have the same name (getName), no parameters, return a String, and have the same body (return name;). The purpose of introducing several elements in one single declaration is that their bodies are the same. The introduction is an error if any of Point, Line, or Square do not have a "name" field. An aspect can introduce fields and methods (even with bodies) onto interfaces as well as classes. Introduction Scope AspectJ allows private and package-protected (default) introduction in addition to public introduction. Private introduction means private in relation to the aspect, not necessarily the target type. So, if an aspect makes a private introduction of a field on a type Then code in the aspect can refer to Foo's x field, but nobody else can. Similarly, if an aspect makes a package-protected introduction, then everything in the aspect's package (which may not be Foo's package) can access x. Example: <literal>PointAssertions</literal> The example below consists of one class and one aspect. The aspect introduces all implementation that is related with assertions of the class. It privately introduces two methods in the class Point, namely assertX and assertY. It also advises the two set methods of Point with before declarations that assert the validity of the given values. The introductions are made privately because other parts of the program have no business accessing the assert methods. Only the code inside of the aspect can call those methods. = 0); } private boolean Point.assertY(int y) { return (y <= 100 && y >= 0); } before(Point p, int x): target(p) && args(x) && call(void setX(int)) { if (!p.assertX(x)) { System.out.println("Illegal value for x"); return; } } before(Point p, int y): target(p) && args(y) && call(void setY(int)) { if (!p.assertY(y)) { System.out.println("Illegal value for y"); return; } } } ]]> Reflection AspectJ provides a special reference variable, thisJoinPoint, that contains reflective information about the current join point for the advice to use. The thisJoinPoint variable can only be used in the context of advice, just like this can only be used in the context of non-static methods and variable initializers. In advice, thisJoinPoint is an object of type JoinPoint. One way to use it is simply to print it out. Like all Java objects, thisJoinPoint has a toString() method that makes quick-and-dirty tracing easy. The type of thisJoinPoint includes a rich reflective class hierarchy of signatures, and can be used to access both static and dynamic information about join points. If, however, only the static information about the join point (such as the Signature) is desired, a lightweight join-point object is available from the thisJoinPointStaticPart special variable. This object is the same object you would get from The static part of a join point does not include dynamic information, such as the arguments, which can be accessed with But it has the performance benefit that repeated execution of the code containing thisJoinPointStaticPart (through, for example, separate method calls) will not result in repeated construction of the reflective object. It is always the case that One more reflective variable is available: thisEnclosingJoinPointStaticPart. This, like thisJoinPointStaticPart, only holds the static part of a join point, but it is not the current but the enclosing join point. So, for example, it is possible to print out the calling source location (if available) with