Copyright (c) 1998-2001 Xerox Corporation, 2002-2003 Palo Alto Research Center, Incorporated. All rights reserved.
This programming guide describes the AspectJ language. A companion guide describes the tools which are part of the AspectJ development environment.
If you are completely new to AspectJ, you should first read Getting Started with AspectJ for a broad overview of programming in AspectJ. If you are already familiar with AspectJ, but want a deeper understanding, you should read The AspectJ Language and look at the examples in the chapter. If you want a more formal definition of AspectJ, you should read Semantics.
Table of Contents
This programming guide does three things. It
The first section, Getting Started with AspectJ, provides a gentle overview of writing AspectJ programs. It also shows how one can introduce AspectJ into an existing development effort in stages, reducing the associated risk. You should read this section if this is your first exposure to AspectJ and you want to get a sense of what AspectJ is all about.
The second section, The AspectJ Language, covers the features of the language in more detail, using code snippets as examples. All the basics of the language is covered, and after reading this section, you should be able to use the language correctly.
The next section, Examples, comprises a set of complete programs that not only show the features being used, but also try to illustrate recommended practice. You should read this section after you are familiar with the elements of AspectJ.
Finally, there are two short chapters, one on Idioms and one on Pitfalls.
The back matter contains several appendices that cover a AspectJ Quick Reference to the language's syntax, a more in depth coverage of its Semantics, and a description of the latitude enjoyed by its Implementation Notes.
Many software developers are attracted to the idea of aspect-oriented programming (AOP) but unsure about how to begin using the technology. They recognize the concept of crosscutting concerns, and know that they have had problems with the implementation of such concerns in the past. But there are many questions about how to adopt AOP into the development process. Common questions include:
This chapter addresses these questions in the context of AspectJ: a general-purpose aspect-oriented extension to Java. A series of abridged examples illustrate the kinds of aspects programmers may want to implement using AspectJ and the benefits associated with doing so. Readers who would like to understand the examples in more detail, or who want to learn how to program examples like these, can find more complete examples and supporting material linked from the AspectJ web site ( http://eclipse.org/aspectj ).
A significant risk in adopting any new technology is going too far too fast. Concern about this risk causes many organizations to be conservative about adopting new technology. To address this issue, the examples in this chapter are grouped into three broad categories, with aspects that are easier to adopt into existing development projects coming earlier in this chapter. The next section, Introduction to AspectJ, we present the core of AspectJ's features, and in Development Aspects, we present aspects that facilitate tasks such as debugging, testing and performance tuning of applications. And, in the section following, Production Aspects, we present aspects that implement crosscutting functionality common in Java applications. We will defer discussing a third category of aspects, reusable aspects, until The AspectJ Language.
These categories are informal, and this ordering is not the only way to adopt AspectJ. Some developers may want to use a production aspect right away. But our experience with current AspectJ users suggests that this is one ordering that allows developers to get experience with (and benefit from) AOP technology quickly, while also minimizing risk.
This section presents a brief introduction to the features of AspectJ used later in this chapter. These features are at the core of the language, but this is by no means a complete overview of AspectJ.
The features are presented using a simple figure editor system. A Figure consists of a number of FigureElements, which can be either Points or Lines. The Figure class provides factory services. There is also a Display. Most example programs later in this chapter are based on this system as well.

UML for the FigureEditor example
The motivation for AspectJ (and likewise for aspect-oriented programming) is the realization that there are issues or concerns that are not well captured by traditional programming methodologies. Consider the problem of enforcing a security policy in some application. By its nature, security cuts across many of the natural units of modularity of the application. Moreover, the security policy must be uniformly applied to any additions as the application evolves. And the security policy that is being applied might itself evolve. Capturing concerns like a security policy in a disciplined way is difficult and error-prone in a traditional programming language.
Concerns like security cut across the natural units of modularity. For object-oriented programming languages, the natural unit of modularity is the class. But in object-oriented programming languages, crosscutting concerns are not easily turned into classes precisely because they cut across classes, and so these aren't reusable, they can't be refined or inherited, they are spread through out the program in an undisciplined way, in short, they are difficult to work with.
Aspect-oriented programming is a way of modularizing crosscutting concerns much like object-oriented programming is a way of modularizing common concerns. AspectJ is an implementation of aspect-oriented programming for Java.
AspectJ adds to Java just one new concept, a join point -- and that's really just a name for an existing Java concept. It adds to Java only a few new constructs: pointcuts, advice, inter-type declarations and aspects. Pointcuts and advice dynamically affect program flow, inter-type declarations statically affects a program's class hierarchy, and aspects encapsulate these new constructs.
A join point is a well-defined point in the program flow. A pointcut picks out certain join points and values at those points. A piece of advice is code that is executed when a join point is reached. These are the dynamic parts of AspectJ.
AspectJ also has different kinds of inter-type declarations that allow the programmer to modify a program's static structure, namely, the members of its classes and the relationship between classes.
AspectJ's aspect are the unit of modularity for crosscutting concerns. They behave somewhat like Java classes, but may also include pointcuts, advice and inter-type declarations.
In the sections immediately following, we are first going to look at join points and how they compose into pointcuts. Then we will look at advice, the code which is run when a pointcut is reached. We will see how to combine pointcuts and advice into aspects, AspectJ's reusable, inheritable unit of modularity. Lastly, we will look at how to use inter-type declarations to deal with crosscutting concerns of a program's class structure.
A critical element in the design of any aspect-oriented language is the join point model. The join point model provides the common frame of reference that makes it possible to define the dynamic structure of crosscutting concerns. This chapter describes AspectJ's dynamic join points, in which join points are certain well-defined points in the execution of the program.
AspectJ provides for many kinds of join points, but this chapter discusses only one of them: method call join points. A method call join point encompasses the actions of an object receiving a method call. It includes all the actions that comprise a method call, starting after all arguments are evaluated up to and including return (either normally or by throwing an exception).
Each method call at runtime is a different join point, even if it comes from the same call expression in the program. Many other join points may run while a method call join point is executing -- all the join points that happen while executing the method body, and in those methods called from the body. We say that these join points execute in the dynamic context of the original call join point.
In AspectJ, pointcuts pick out certain join points in the program flow. For example, the pointcut
call(void Point.setX(int))
picks out each join point that is a call to a method that has the signature void Point.setX(int) — that is, Point's void setX method with a single int parameter.
A pointcut can be built out of other pointcuts with and, or, and not (spelled &&, ||, and !). For example:
call(void Point.setX(int)) || call(void Point.setY(int))
picks out each join point that is either a call to setX or a call to setY.
Pointcuts can identify join points from many different types — in other words, they can crosscut types. For example,
call(void FigureElement.setXY(int,int)) || call(void Point.setX(int)) || call(void Point.setY(int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point));
picks out each join point that is a call to one of five methods (the first of which is an interface method, by the way).
In our example system, this pointcut captures all the join points when a FigureElement moves. While this is a useful way to specify this crosscutting concern, it is a bit of a mouthful. So AspectJ allows programmers to define their own named pointcuts with the pointcut form. So the following declares a new, named pointcut:
pointcut move():
call(void FigureElement.setXY(int,int)) ||
call(void Point.setX(int)) ||
call(void Point.setY(int)) ||
call(void Line.setP1(Point)) ||
call(void Line.setP2(Point));
and whenever this definition is visible, the programmer can simply use move() to capture this complicated pointcut.
The previous pointcuts are all based on explicit enumeration of a set of method signatures. We sometimes call this name-based crosscutting. AspectJ also provides mechanisms that enable specifying a pointcut in terms of properties of methods other than their exact name. We call this property-based crosscutting. The simplest of these involve using wildcards in certain fields of the method signature. For example, the pointcut
call(void Figure.make*(..))
picks out each join point that's a call to a void method defined on Figure whose the name begins with "make" regardless of the method's parameters. In our system, this picks out calls to the factory methods makePoint and makeLine. The pointcut
call(public * Figure.* (..))
picks out each call to Figure's public methods.
But wildcards aren't the only properties AspectJ supports. Another pointcut, cflow, identifies join points based on whether they occur in the dynamic context of other join points. So
cflow(move())
picks out each join point that occurs in the dynamic context of the join points picked out by move(), our named pointcut defined above. So this picks out each join points that occurrs between when a move method is called and when it returns (either normally or by throwing an exception).
So pointcuts pick out join points. But they don't do anything apart from picking out join points. To actually implement crosscutting behavior, we use advice. Advice brings together a pointcut (to pick out join points) and a body of code (to run at each of those join points).
AspectJ has several different kinds of advice. Before advice runs as a join point is reached, before the program proceeds with the join point. For example, before advice on a method call join point runs before the actual method starts running, just after the arguments to the method call are evaluated.
before(): move() {
System.out.println("about to move");
}
After advice on a particular join point runs after the program proceeds with that join point. For example, after advice on a method call join point runs after the method body has run, just before before control is returned to the caller. Because Java programs can leave a join point 'normally' or by throwing an exception, there are three kinds of after advice: after returning, after throwing, and plain after (which runs after returning or throwing, like Java's finally).
after() returning: move() {
System.out.println("just successfully moved");
}
Around advice on a join point runs as the join point is reached, and has explicit control over whether the program proceeds with the join point. Around advice is not discussed in this section.
Pointcuts not only pick out join points, they can also expose part of the execution context at their join points. Values exposed by a pointcut can be used in the body of advice declarations.
An advice declaration has a parameter list (like a method) that gives names to all the pieces of context that it uses. For example, the after advice
after(FigureElement fe, int x, int y) returning:
...SomePointcut... {
...SomeBody...
}
uses three pieces of exposed context, a FigureElement named fe, and two ints named x and y.
The body of the advice uses the names just like method parameters, so
after(FigureElement fe, int x, int y) returning:
...SomePointcut... {
System.out.println(fe + " moved to (" + x + ", " + y + ")");
}
The advice's pointcut publishes the values for the advice's arguments. The three primitive pointcuts this, target and args are used to publish these values. So now we can write the complete piece of advice:
after(FigureElement fe, int x, int y) returning:
call(void FigureElement.setXY(int, int))
&& target(fe)
&& args(x, y) {
System.out.println(fe + " moved to (" + x + ", " + y + ")");
}
The pointcut exposes three values from calls to setXY: the target FigureElement -- which it publishes as fe, so it becomes the first argument to the after advice -- and the two int arguments -- which it publishes as x and y, so they become the second and third argument to the after advice.
So the advice prints the figure element that was moved and its new x and y coordinates after each setXY method call.
A named pointcut may have parameters like a piece of advice. When the named pointcut is used (by advice, or in another named pointcut), it publishes its context by name just like the this, target and args pointcut. So another way to write the above advice is
pointcut setXY(FigureElement fe, int x, int y):
call(void FigureElement.setXY(int, int))
&& target(fe)
&& args(x, y);
after(FigureElement fe, int x, int y) returning: setXY(fe, x, y) {
System.out.println(fe + " moved to (" + x + ", " + y + ").");
}
Inter-type declarations in AspectJ are declarations that cut across classes and their hierarchies. They may declare members that cut across multiple classes, or change the inheritance relationship between classes. Unlike advice, which operates primarily dynamically, introduction operates statically, at compile-time.
Consider the problem of expressing a capability shared by some existing classes that are already part of a class hierarchy, i.e. they already extend a class. In Java, one creates an interface that captures this new capability, and then adds to each affected class a method that implements this interface.
AspectJ can express the concern in one place, by using inter-type declarations. The aspect declares the methods and fields that are necessary to implement the new capability, and associates the methods and fields to the existing classes.
Suppose we want to have Screen objects observe changes to Point objects, where Point is an existing class. We can implement this by writing an aspect declaring that the class Point Point has an instance field, observers, that keeps track of the Screen objects that are observing Points.
aspect PointObserving {
private Vector Point.observers = new Vector();
...
}
The observers field is private, so only PointObserving can see it. So observers are added or removed with the static methods addObserver and removeObserver on the aspect.
aspect PointObserving {
private Vector Point.observers = new Vector();
public static void addObserver(Point p, Screen s) {
p.observers.add(s);
}
public static void removeObserver(Point p, Screen s) {
p.observers.remove(s);
}
...
}
Along with this, we can define a pointcut changes that defines what we want to observe, and the after advice defines what we want to do when we observe a change.
aspect PointObserving {
private Vector Point.observers = new Vector();
public static void addObserver(Point p, Screen s) {
p.observers.add(s);
}
public static void removeObserver(Point p, Screen s) {
p.observers.remove(s);
}
pointcut changes(Point p): target(p) && call(void Point.set*(int));
after(Point p): changes(p) {
Iterator iter = p.observers.iterator();
while ( iter.hasNext() ) {
updateObserver(p, (Screen)iter.next());
}
}
static void updateObserver(Point p, Screen s) {
s.display(p);
}
}
Note that neither Screen's nor Point's code has to be modified, and that all the changes needed to support this new capability are local to this aspect.
Aspects wrap up pointcuts, advice, and inter-type declarations in a a modular unit of crosscutting implementation. It is defined very much like a class, and can have methods, fields, and initializers in addition to the crosscutting members. Because only aspects may include these crosscutting members, the declaration of these effects is localized.
Like classes, aspects may be instantiated, but AspectJ controls how that instantiation happens -- so you can't use Java's new form to build new aspect instances. By default, each aspect is a singleton, so one aspect instance is created. This means that advice may use non-static fields of the aspect, if it needs to keep state around:
aspect Logging {
OutputStream logStream = System.err;
before(): move() {
logStream.println("about to move");
}
}
Aspects may also have more complicated rules for instantiation, but these will be described in a later chapter.
The next two sections present the use of aspects in increasingly sophisticated ways. Development aspects are easily removed from production builds. Production aspects are intended to be used in both development and in production, but tend to affect only a few classes.
This section presents examples of aspects that can be used during development of Java applications. These aspects facilitate debugging, testing and performance tuning work. The aspects define behavior that ranges from simple tracing, to profiling, to testing of internal consistency within the application. Using AspectJ makes it possible to cleanly modularize this kind of functionality, thereby making it possible to easily enable and disable the functionality when desired.
This first example shows how to increase the visibility of the internal workings of a program. It is a simple tracing aspect that prints a message at specified method calls. In our figure editor example, one such aspect might simply trace whenever points are drawn.
aspect SimpleTracing {
pointcut tracedCall():
call(void FigureElement.draw(GraphicsContext));
before(): tracedCall() {
System.out.println("Entering: " + thisJoinPoint);
}
}
This code makes use of the thisJoinPoint special variable. Within all advice bodies this variable is bound to an object that describes the current join point. The effect of this code is to print a line like the following every time a figure element receives a draw method call:
Entering: call(void FigureElement.draw(GraphicsContext))
To understand the benefit of coding this with AspectJ consider changing the set of method calls that are traced. With AspectJ, this just requires editing the definition of the tracedCalls pointcut and recompiling. The individual methods that are traced do not need to be edited.
When debugging, programmers often invest considerable effort in figuring out a good set of trace points to use when looking for a particular kind of problem. When debugging is complete or appears to be complete it is frustrating to have to lose that investment by deleting trace statements from the code. The alternative of just commenting them out makes the code look bad, and can cause trace statements for one kind of debugging to get confused with trace statements for another kind of debugging.
With AspectJ it is easy to both preserve the work of designing a good set of trace points and disable the tracing when it isn t being used. This is done by writing an aspect specifically for that tracing mode, and removing that aspect from the compilation when it is not needed.
This ability to concisely implement and reuse debugging configurations that have proven useful in the past is a direct result of AspectJ modularizing a crosscutting design element the set of methods that are appropriate to trace when looking for a given kind of information.
Our second example shows you how to do some very specific profiling. Although many sophisticated profiling tools are available, and these can gather a variety of information and display the results in useful ways, you may sometimes want to profile or log some very specific behavior. In these cases, it is often possible to write a simple aspect similar to the ones above to do the job.
For example, the following aspect counts the number of calls to the rotate method on a Line and the number of calls to the set* methods of a Point that happen within the control flow of those calls to rotate:
aspect SetsInRotateCounting {
int rotateCount = 0;
int setCount = 0;
before(): call(void Line.rotate(double)) {
rotateCount++;
}
before(): call(void Point.set*(int))
&& cflow(call(void Line.rotate(double))) {
setCount++;
}
}
In effect, this aspect allows the programmer to ask very specific questions like
How many times is the rotate method defined on Line objects called?and
How many times are methods defined on Point objects whose name begins with "set" called in fulfilling those rotate calls?questions it may be difficult to express using standard profiling or logging tools.
Many programmers use the "Design by Contract" style popularized by Bertand Meyer in Object-Oriented Software Construction, 2/e. In this style of programming, explicit pre-conditions test that callers of a method call it properly and explicit post-conditions test that methods properly do the work they are supposed to.
AspectJ makes it possible to implement pre- and post-condition testing in modular form. For example, this code
aspect PointBoundsChecking {
pointcut setX(int x):
(call(void FigureElement.setXY(int, int)) && args(x, *))
|| (call(void Point.setX(int)) && args(x));
pointcut setY(int y):
(call(void FigureElement.setXY(int, int)) && args(*, y))
|| (call(void Point.setY(int)) && args(y));
before(int x): setX(x) {
if ( x < MIN_X || x > MAX_X )
throw new IllegalArgumentException("x is out of bounds.");
}
before(int y): setY(y) {
if ( y < MIN_Y || y > MAX_Y )
throw new IllegalArgumentException("y is out of bounds.");
}
}
implements the bounds checking aspect of pre-condition testing for operations that move points. Notice that the setX pointcut refers to all the operations that can set a Point's x coordinate; this includes the setX method, as well as half of the setXY method. In this sense the setX pointcut can be seen as involving very fine-grained crosscutting — it names the the setX method and half of the setXY method.
Even though pre- and post-condition testing aspects can often be used only during testing, in some cases developers may wish to include them in the production build as well. Again, because AspectJ makes it possible to modularize these crosscutting concerns cleanly, it gives developers good control over this decision.
The property-based crosscutting mechanisms can be very useful in defining more sophisticated contract enforcement. One very powerful use of these mechanisms is to identify method calls that, in a correct program, should not exist. For example, the following aspect enforces the constraint that only the well-known factory methods can add an element to the registry of figure elements. Enforcing this constraint ensures that no figure element is added to the registry more than once.
aspect RegistrationProtection {
pointcut register(): call(void Registry.register(FigureElement));
pointcut canRegister(): withincode(static * FigureElement.make*(..));
before(): register() && !canRegister() {
throw new IllegalAccessException("Illegal call " + thisJoinPoint);
}
}
This aspect uses the withincode primitive pointcut to denote all join points that occur within the body of the factory methods on FigureElement (the methods with names that begin with "make"). This is a property-based pointcut because it identifies join points based not on their signature, but rather on the property that they occur specifically within the code of another method. The before advice declaration effectively says signal an error for any calls to register that are not within the factory methods.
This advice throws a runtime exception at certain join points, but AspectJ can do better. Using the declare error form, we can have the compiler signal the error.
aspect RegistrationProtection {
pointcut register(): call(void Registry.register(FigureElement));
pointcut canRegister(): withincode(static * FigureElement.make*(..));
declare error: register() && !canRegister(): "Illegal call"
}
When using this aspect, it is impossible for the compiler to compile programs with these illegal calls. This early detection is not always possible. In this case, since we depend only on static information (the withincode pointcut picks out join points totally based on their code, and the call pointcut here picks out join points statically). Other enforcement, such as the precondition enforcement, above, does require dynamic information such as the runtime value of parameters.
Configuration management for aspects can be handled using a variety of make-file like techniques. To work with optional aspects, the programmer can simply define their make files to either include the aspect in the call to the AspectJ compiler or not, as desired.
Developers who want to be certain that no aspects are included in the production build can do so by configuring their make files so that they use a traditional Java compiler for production builds. To make it easy to write such make files, the AspectJ compiler has a command-line interface that is consistent with ordinary Java compilers.
This section presents examples of aspects that are inherently intended to be included in the production builds of an application. Production aspects tend to add functionality to an application rather than merely adding more visibility of the internals of a program. Again, we begin with name-based aspects and follow with property-based aspects. Name-based production aspects tend to affect only a small number of methods. For this reason, they are a good next step for projects adopting AspectJ. But even though they tend to be small and simple, they can often have a significant effect in terms of making the program easier to understand and maintain.
The first example production aspect shows how one might implement some simple functionality where it is problematic to try and do it explicitly. It supports the code that refreshes the display. The role of the aspect is to maintain a dirty bit indicating whether or not an object has moved since the last time the display was refreshed.
Implementing this functionality as an aspect is straightforward. The testAndClear method is called by the display code to find out whether a figure element has moved recently. This method returns the current state of the dirty flag and resets it to false. The pointcut move captures all the method calls that can move a figure element. The after advice on move sets the dirty flag whenever an object moves.
aspect MoveTracking {
private static boolean dirty = false;
public static boolean testAndClear() {
boolean result = dirty;
dirty = false;
return result;
}
pointcut move():
call(void FigureElement.setXY(int, int)) ||
call(void Line.setP1(Point)) ||
call(void Line.setP2(Point)) ||
call(void Point.setX(int)) ||
call(void Point.setY(int));
after() returning: move() {
dirty = true;
}
}
Even this simple example serves to illustrate some of the important benefits of using AspectJ in production code. Consider implementing this functionality with ordinary Java: there would likely be a helper class that contained the dirty flag, the testAndClear method, as well as a setFlag method. Each of the methods that could move a figure element would include a call to the setFlag method. Those calls, or rather the concept that those calls should happen at each move operation, are the crosscutting concern in this case.
The AspectJ implementation has several advantages over the standard implementation:
The structure of the crosscutting concern is captured explicitly. The moves pointcut clearly states all the methods involved, so the programmer reading the code sees not just individual calls to setFlag, but instead sees the real structure of the code. The IDE support included with AspectJ automatically reminds the programmer that this aspect advises each of the methods involved. The IDE support also provides commands to jump to the advice from the method and vice-versa.
Evolution is easier. If, for example, the aspect needs to be revised to record not just that some figure element moved, but rather to record exactly which figure elements moved, the change would be entirely local to the aspect. The pointcut would be updated to expose the object being moved, and the advice would be updated to record that object. The paper An Overview of AspectJ (available linked off of the AspectJ web site -- http://eclipse.org/aspectj), presented at ECOOP 2001, presents a detailed discussion of various ways this aspect could be expected to evolve.
The functionality is easy to plug in and out. Just as with development aspects, production aspects may need to be removed from the system, either because the functionality is no longer needed at all, or because it is not needed in certain configurations of a system. Because the functionality is modularized in a single aspect this is easy to do.
The implementation is more stable. If, for example, the programmer adds a subclass of Line that overrides the existing methods, this advice in this aspect will still apply. In the ordinary Java implementation the programmer would have to remember to add the call to setFlag in the new overriding method. This benefit is often even more compelling for property-based aspects (see the section Providing Consistent Behavior).
The crosscutting structure of context passing can be a significant source of complexity in Java programs. Consider implementing functionality that would allow a client of the figure editor (a program client rather than a human) to set the color of any figure elements that are created. Typically this requires passing a color, or a color factory, from the client, down through the calls that lead to the figure element factory. All programmers are familiar with the inconvenience of adding a first argument to a number of methods just to pass this kind of context information.
Using AspectJ, this kind of context passing can be implemented in a modular way. The following code adds after advice that runs only when the factory methods of Figure are called in the control flow of a method on a ColorControllingClient.
aspect ColorControl {
pointcut CCClientCflow(ColorControllingClient client):
cflow(call(* * (..)) && target(client));
pointcut make(): call(FigureElement Figure.make*(..));
after (ColorControllingClient c) returning (FigureElement fe):
make() && CCClientCflow(c) {
fe.setColor(c.colorFor(fe));
}
}
This aspect affects only a small number of methods, but note that the non-AOP implementation of this functionality might require editing many more methods, specifically, all the methods in the control flow from the client to the factory. This is a benefit common to many property-based aspects while the aspect is short and affects only a modest number of benefits, the complexity the aspect saves is potentially much larger.
This example shows how a property-based aspect can be used to provide consistent handling of functionality across a large set of operations. This aspect ensures that all public methods of the com.bigboxco package log any Errors they throw to their caller (in Java, an Error is like an Exception, but it indicates that something really bad and usually unrecoverable has happened). The publicMethodCall pointcut captures the public method calls of the package, and the after advice runs whenever one of those calls throws an Error. The advice logs that Error and then the throw resumes.
aspect PublicErrorLogging {
Log log = new Log();
pointcut publicMethodCall():
call(public * com.bigboxco.*.*(..));
after() throwing (Error e): publicMethodCall() {
log.write(e);
}
}
In some cases this aspect can log an exception twice. This happens if code inside the com.bigboxco package itself calls a public method of the package. In that case this code will log the error at both the outermost call into the com.bigboxco package and the re-entrant call. The cflow primitive pointcut can be used in a nice way to exclude these re-entrant calls:
after() throwing (Error e):
publicMethodCall() && !cflow(publicMethodCall()) {
log.write(e);
}
The following aspect is taken from work on the AspectJ compiler. The aspect advises about 35 methods in the JavaParser class. The individual methods handle each of the different kinds of elements that must be parsed. They have names like parseMethodDec, parseThrows, and parseExpr.
aspect ContextFilling {
pointcut parse(JavaParser jp):
call(* JavaParser.parse*(..))
&& target(jp)
&& !call(Stmt parseVarDec(boolean)); // var decs
// are tricky
around(JavaParser jp) returns ASTObject: parse(jp) {
Token beginToken = jp.peekToken();
ASTObject ret = proceed(jp);
if (ret != null) jp.addContext(ret, beginToken);
return ret;
}
}
This example exhibits a property found in many aspects with large property-based pointcuts. In addition to a general property based pattern call(* JavaParser.parse*(..)) it includes an exception to the pattern !call(Stmt parseVarDec(boolean)). The exclusion of parseVarDec happens because the parsing of variable declarations in Java is too complex to fit with the clean pattern of the other parse* methods. Even with the explicit exclusion this aspect is a clear expression of a clean crosscutting modularity. Namely that all parse* methods that return ASTObjects, except for parseVarDec share a common behavior for establishing the parse context of their result.
The process of writing an aspect with a large property-based pointcut, and of developing the appropriate exceptions can clarify the structure of the system. This is especially true, as in this case, when refactoring existing code to use aspects. When we first looked at the code for this aspect, we were able to use the IDE support provided in AJDE for JBuilder to see what methods the aspect was advising compared to our manual coding. We quickly discovered that there were a dozen places where the aspect advice was in effect but we had not manually inserted the required functionality. Two of these were bugs in our prior non-AOP implementation of the parser. The other ten were needless performance optimizations. So, here, refactoring the code to express the crosscutting structure of the aspect explicitly made the code more concise and eliminated latent bugs.
AspectJ is a simple and practical aspect-oriented extension to Java. With just a few new constructs, AspectJ provides support for modular implementation of a range of crosscutting concerns.
Adoption of AspectJ into an existing Java development project can be a straightforward and incremental task. One path is to begin by using only development aspects, going on to using production aspects and then reusable aspects after building up experience with AspectJ. Adoption can follow other paths as well. For example, some developers will benefit from using production aspects right away. Others may be able to write clean reusable aspects almost right away.
AspectJ enables both name-based and property based crosscutting. Aspects that use name-based crosscutting tend to affect a small number of other classes. But despite their small scale, they can often eliminate significant complexity compared to an ordinary Java implementation. Aspects that use property-based crosscutting can have small or large scale.
Using AspectJ results in clean well-modularized implementations of crosscutting concerns. When written as an AspectJ aspect the structure of a crosscutting concern is explicit and easy to understand. Aspects are also highly modular, making it possible to develop plug-and-play implementations of crosscutting functionality.
AspectJ provides more functionality than was covered by this short introduction. The next chapter, The AspectJ Language, covers in detail more of the features of the AspectJ language. The following chapter, Examples, then presents some carefully chosen examples that show you how AspectJ might be used. We recommend that you read the next two chapters carefully before deciding to adopt AspectJ into a project.
Table of Contents
The previous chapter, Getting Started with AspectJ, 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.
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.
Here's an example of an aspect definition in AspectJ:
1 aspect FaultHandler {
2
3 private boolean Server.disabled = false;
4
5 private void reportFault() {
6 System.out.println("Failure! Please fix it.");
7 }
8
9 public static void fixServer(Server s) {
10 s.disabled = false;
11 }
12
13 pointcut services(Server s): target(s) && call(public * *(..));
14
15 before(Server s): services(s) {
16 if (s.disabled) throw new DisabledException();
17 }
18
19 after(Server s) throwing (FaultException e): services(s) {
20 s.disabled = true;
21 reportFault();
22 }
23 }
The FaultHandler consists of one inter-type field on Server (line 03), two methods (lines 05-07 and 09-11), one pointcut definition (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 of other program entities, ordinary variables and methods, pointcut definitions, inter-type declarations, and advice, where advice may be before, after or around advice. The remainder of this lesson focuses on those crosscut-related constructs.
AspectJ's pointcut definitions give names to pointcuts. Pointcuts themselves pick out join points, i.e. interesting points in the execution of a program. These join points can be method or constructor invocations and executions, the handling of exceptions, field assignments and accesses, etc. Take, for example, the pointcut definition in line 13:
pointcut services(Server s): target(s) && call(public * *(..))
This pointcut, named services, picks out those points in the execution of the program when Server objects have their public methods called. It also allows anyone using the services pointcut to access the Server object whose method is being 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.
Pointcuts pick out arbitrarily large numbers of join points of a program. But they pick out only a small number of kinds of join points. Those kinds of join points correspond to some of the most important concepts in Java. Here is an incomplete list: method call, method execution, exception handling, instantiation, constructor execution, and field access. Each kind of join point can be picked out by its own specialized pointcut that you will learn about in other parts of this guide.
A piece of advice brings together a pointcut and a body of code to define aspect implementation that runs at join points picked out by the pointcut. For example, the advice in lines 15-17 specifies that the following piece of code
{
if (s.disabled) throw new DisabledException();
}
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:
{
s.disabled = true;
reportFault();
}
But this second method executes after those operations throw exception of type FaultException.
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.
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 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
Pointcuts compose through the operations or ("||"), and ("&&") and not ("!").
You can select methods and constructors based on their modifiers and on negations of modifiers. For example, you can say:
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(P) picks out each join point 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 each join point that is 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 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(A) pointcut above is required to avoid the 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 Points, 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 {}
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:
pointcut setter(Point p1, int newval): target(p1) && args(newval)
(call(void setX(int) ||
call(void setY(int)));
before(Point p1, int newval): setter(p1, newval) {
System.out.println("About to set something in " + p1 +
" to the new value " + newval);
}
And here is exactly the same example, but using an anonymous pointcut:
before(Point p1, int newval): target(p1) && args(newval)
(call(void setX(int)) ||
call(void setY(int))) {
System.out.println("About to set something in " + p1 +
" to the new value " + newval);
}
Here are examples of the different advice:
This before advice runs just before the join points picked out by the (anonymous) pointcut:
before(Point p, int x): target(p) && args(x) && call(void setX(int)) {
if (!p.assertX(x)) return;
}
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:
after(Point p, int x): target(p) && args(x) && call(void setX(int)) {
if (!p.assertX(x)) throw new PostConditionViolation();
}
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:
after(Point p) returning(int x): target(p) && call(int getX()) {
System.out.println("Returning int value " + x + " for p = " + p);
}
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:
after() throwing(Exception e): target(Point) && call(void setX(int)) {
System.out.println(e);
}
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:
void around(Point p, int x): target(p)
&& args(x)
&& call(void setX(int)) {
if (p.assertX(x)) proceed(p, x);
p.releaseResources();
}
Aspects can declare members (fields, methods, and constructors) that are owned by other types. These are called inter-type members. Aspects can also declare that other types implement new interfaces or extend a new class. Here are examples of some such inter-type declarations:
This declares that each Server has a boolean field named disabled, initialized to false:
private boolean Server.disabled = false;It is declared private, which means that it is private to the aspect: only code in the aspect can see the field. And even if Server has another private field named disabled (declared in Server or in another aspect) there won't be a name collision, since no reference to disabled will be ambiguous.
This declares that each Point has an int method named getX with no arguments that returns whatever this.x is:
public int Point.getX() { return this.x; }
Inside the body, this is the
Point object currently executing. Because the
method is publically declared any code can call it, but if there is
some other Point.getX() declared there will be a
compile-time conflict.
This publically declares a two-argument constructor for Point:
public Point.new(int x, int y) { this.x = x; this.y = y; }
This publicly declares that each Point has an int field named x, initialized to zero:
public int Point.x = 0;Because this is publically declared, it is an error if Point already has a field named x (defined by Point or by another aspect).
This declares that the Point class implements the Comparable interface:
declare parents: Point implements Comparable;Of course, this will be an error unless Point defines the methods required by Comparable.
This declares that the Point class extends the GeometricObject class.
declare parents: Point extends GeometricObject;
An aspect can have several inter-type declarations. For example, the following declarations
public String Point.name;
public void Point.setName(String name) { this.name = name; }
publicly declare that Point has both a String field
name and a void method
setName(String) (which refers to the
name field declared by the aspect).
An inter-type member can only have one target type, but often you may wish to declare the same member on more than one type. This can be done by using an inter-type member in combination with a private interface:
aspect A {
private interface HasName {}
declare parents: (Point || Line || Square) implements HasName;
private String HasName.name;
public String HasName.getName() { return name; }
}
This declares a marker interface HasName, and also declares that any
type that is either Point,
Line, or Square implements that
interface. It also privately declares that all HasName
object have a String field called
name, and publically declares that all
HasName objects have a String
method getName() (which refers to the privately
declared name field).
As you can see from the above example, an aspect can declare that interfaces have fields and methods, even non-constant fields and methods with bodies.
AspectJ allows private and package-protected (default) inter-type declarations in addition to public inter-type declarations. Private means private in relation to the aspect, not necessarily the target type. So, if an aspect makes a private inter-type declaration of a field
private int Foo.x;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,
int Foo.x;
then everything in the aspect's package (which may or may not be Foo's package) can access x.
The example below consists of one class and one aspect. The aspect privately declares the assertion methods of Point, assertX and assertY. It also guards calls to setX and setY with calls to these assertion methods. The assertion methods are declared privately because other parts of the program (including the code in Point) have no business accessing the assert methods. Only the code inside of the aspect can call those methods.
class Point {
int x, y;
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public static void main(String[] args) {
Point p = new Point();
p.setX(3); p.setY(333);
}
}
aspect PointAssertions {
private boolean Point.assertX(int x) {
return (x <= 100 && x >= 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;
}
}
}
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 org.aspectj.lang.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:
class TraceNonStaticMethods {
before(Point p): target(p) && call(* *(..)) {
System.out.println("Entering " + thisJoinPoint + " in " + p);
}
}
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 such as the arguments of the join point:
thisJoinPoint.getArgs()In addition, it holds an object consisting of all the static information about the join point such as corresponding line number and static signature:
thisJoinPoint.getStaticPart()If you only need the static information about the join point, you may access the static part of the join point directly with the special variable thisJoinPointStaticPart. Using thisJoinPointStaticPart will avoid the run-time creation of the join point object that may be necessary when using thisJoinPoint directly.
It is always the case that
thisJoinPointStaticPart == thisJoinPoint.getStaticPart() thisJoinPoint.getKind() == thisJoinPointStaticPart.getKind() thisJoinPoint.getSignature() == thisJoinPointStaticPart.getSignature() thisJoinPoint.getSourceLocation() == thisJoinPointStaticPart.getSourceLocation()
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
before() : execution (* *(..)) {
System.err.println(thisEnclosingJoinPointStaticPart.getSourceLocation())
}
Table of Contents
This chapter consists entirely of examples of AspectJ use.
The examples can be grouped into four categories:
| technique | Examples which illustrate how to use one or more features of the language. |
| development | Examples of using AspectJ during the development phase of a project. |
| production | Examples of using AspectJ to provide functionality in an application. |
| reusable | Examples of reuse of aspects and pointcuts. |
The examples source code is part of the AspectJ distribution which may be downloaded from the AspectJ project page ( http://eclipse.org/aspectj ).
Compiling most examples is straightforward. Go the InstallDir/examples directory, and look for a .lst file in one of the example subdirectories. Use the -arglist option to ajc to compile the example. For instance, to compile the telecom example with billing, type
ajc -argfile telecom/billing.lst
To run the examples, your classpath must include the AspectJ run-time Java archive (aspectjrt.jar). You may either set the CLASSPATH environment variable or use the -classpath command line option to the Java interpreter:
(In Unix use a : in the CLASSPATH) java -classpath ".:InstallDir/lib/aspectjrt.jar" telecom.billingSimulation
(In Windows use a ; in the CLASSPATH) java -classpath ".;InstallDir/lib/aspectjrt.jar" telecom.billingSimulation
This section presents two basic techniques of using AspectJ, one each from the two fundamental ways of capturing crosscutting concerns: with dynamic join points and advice, and with static introduction. Advice changes an application's behavior. Introduction changes both an application's behavior and its structure.
The first example, the section called “Join Points and thisJoinPoint”, is about gathering and using information about the join point that has triggered some advice. The second example, the section called “Roles and Views”, concerns a crosscutting view of an existing class hierarchy.
(The code for this example is in InstallDir/examples/tjp.)
A join point is some point in the execution of a program together with a view into the execution context when that point occurs. Join points are picked out by pointcuts. When a program reaches a join point, advice on that join point may run in addition to (or instead of) the join point itself.
When using a pointcut that picks out join points of a single kind by name, typicaly the the advice will know exactly what kind of join point it is associated with. The pointcut may even publish context about the join point. Here, for example, since the only join points picked out by the pointcut are calls of a certain method, we can get the target value and one of the argument values of the method calls directly.
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;
}
}
But sometimes the shape of the join point is not so clear. For instance, suppose a complex application is being debugged, and we want to trace when any method of some class is executed. The pointcut
pointcut execsInProblemClass(): within(ProblemClass)
&& execution(* *(..));
will pick out each execution join point of every method defined within ProblemClass. Since advice executes at each join point picked out by the pointcut, we can reasonably ask which join point was reached.
Information about the join point that was matched is available to advice through the special variable thisJoinPoint, of type org.aspectj.lang.JoinPoint. Through this object we can access information such as
The class tjp.Demo in tjp/Demo.java defines two methods foo and bar with different parameter lists and return types. Both are called, with suitable arguments, by Demo's go method which was invoked from within its main method.
public class Demo {
static Demo d;
public static void main(String[] args){
new Demo().go();
}
void go(){
d = new Demo();
d.foo(1,d);
System.out.println(d.bar(new Integer(3)));
}
void foo(int i, Object o){
System.out.println("Demo.foo(" + i + ", " + o + ")\n");
}
String bar (Integer j){
System.out.println("Demo.bar(" + j + ")\n");
return "Demo.bar(" + j + ")";
}
}
This aspect uses around advice to intercept the execution of methods foo and bar in Demo, and prints out information garnered from thisJoinPoint to the console.
aspect GetInfo {
static final void println(String s){ System.out.println(s); }
pointcut goCut(): cflow(this(Demo) && execution(void go()));
pointcut demoExecs(): within(Demo) && execution(* *(..));
Object around(): demoExecs() && !execution(* go()) && goCut() {
println("Intercepted message: " +
thisJoinPointStaticPart.getSignature().getName());
println("in class: " +
thisJoinPointStaticPart.getSignature().getDeclaringType().getName());
printParameters(thisJoinPoint);
println("Running original method: \n" );
Object result = proceed();
println(" result: " + result );
return result;
}
static private void printParameters(JoinPoint jp) {
println("Arguments: " );
Object[] args = jp.getArgs();
String[] names = ((CodeSignature)jp.getSignature()).getParameterNames();
Class[] types = ((CodeSignature)jp.getSignature()).getParameterTypes();
for (int i = 0; i < args.length; i++) {
println(" " + i + ". " + names[i] +
" : " + types[i].getName() +
" = " + args[i]);
}
}
}
The pointcut goCut is defined as
cflow(this(Demo)) && execution(void go())so that only executions made in the control flow of Demo.go are intercepted. The control flow from the method go includes the execution of go itself, so the definition of the around advice includes !execution(* go()) to exclude it from the set of executions advised.
The name of the method and that method's defining class are available as parts of the org.aspectj.lang.Signature object returned by calling getSignature() on either thisJoinPoint or thisJoinPointStaticPart.
The static portions of the parameter details, the name and types of the parameters, can be accessed through the org.aspectj.lang.reflect.CodeSignature associated with the join point. All execution join points have code signatures, so the cast to CodeSignature cannot fail.
The dynamic portions of the parameter details, the actual values of the parameters, are accessed directly from the execution join point object.
(The code for this example is in InstallDir/examples/introduction.)
Like advice, inter-type declarations are members of an aspect. They declare members that act as if they were defined on another class. Unlike advice, inter-type declarations affect not only the behavior of the application, but also the structural relationship between an application's classes.
This is crucial: Publically affecting the class structure of an application makes these modifications available to other components of the application.
Aspects can declare inter-type
and can also declare that target typesThis example provides three illustrations of the use of inter-type declarations to encapsulate roles or views of a class. The class our aspect will be dealing with, Point, is a simple class with rectangular and polar coordinates. Our inter-type declarations will make the class Point, in turn, cloneable, hashable, and comparable. These facilities are provided by AspectJ without having to modify the code for the class Point.
The Point class defines geometric points whose interface includes polar and rectangular coordinates, plus some simple operations to relocate points. Point's implementation has attributes for both its polar and rectangular coordinates, plus flags to indicate which currently reflect the position of the point. Some operations cause the polar coordinates to be updated from the rectangular, and some have the opposite effect. This implementation, which is in intended to give the minimum number of conversions between coordinate systems, has the property that not all the attributes stored in a Point object are necessary to give a canonical representation such as might be used for storing, comparing, cloning or making hash codes from points. Thus the aspects, though simple, are not totally trivial.
The diagram below gives an overview of the aspects and their interaction with the class Point.
This first aspect is responsible for Point's implementation of the Cloneable interface. It declares that Point implements Cloneable with a declare parents form, and also publically declares a specialized Point's clone() method. In Java, all objects inherit the method clone from the class Object, but an object is not cloneable unless its class also implements the interface Cloneable. In addition, classes frequently have requirements over and above the simple bit-for-bit copying that Object.clone does. In our case, we want to update a Point's coordinate systems before we actually clone the Point. So our aspect makes sure that Point overrides Object.clone with a new method that does what we want.
We also define a test main method in the aspect for convenience.
public aspect CloneablePoint {
declare parents: Point implements Cloneable;
public Object Point.clone() throws CloneNotSupportedException {
// we choose to bring all fields up to date before cloning.
makeRectangular();
makePolar();
return super.clone();
}
public static void main(String[] args){
Point p1 = new Point();
Point p2 = null;
p1.setPolar(Math.PI, 1.0);
try {
p2 = (Point)p1.clone();
} catch (CloneNotSupportedException e) {}
System.out.println("p1 =" + p1 );
System.out.println("p2 =" + p2 );
p1.rotate(Math.PI / -2);
System.out.println("p1 =" + p1 );
System.out.println("p2 =" + p2 );
}
}
ComparablePoint is responsible for Point's implementation of the Comparable interface.
The interface Comparable defines the single method compareTo which can be use to define a natural ordering relation among the objects of a class that implement it.
ComparablePoint uses declare parents to declare that Point implements Comparable, and also publically declares the appropriate compareTo(Object) method: A Point p1 is said to be less than another Point p2 if p1 is closer to the origin.
We also define a test main method in the aspect for convenience.
public aspect ComparablePoint {
declare parents: Point implements Comparable;
public int Point.compareTo(Object o) {
return (int) (this.getRho() - ((Point)o).getRho());
}
public static void main(String[] args){
Point p1 = new Point();
Point p2 = new Point();
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
p1.setRectangular(2,5);
p2.setRectangular(2,5);
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
p2.setRectangular(3,6);
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
p1.setPolar(Math.PI, 4);
p2.setPolar(Math.PI, 4);
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
p1.rotate(Math.PI / 4.0);
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
p1.offset(1,1);
System.out.println("p1 =?= p2 :" + p1.compareTo(p2));
}
}
Our third aspect is responsible for Point's overriding of Object's equals and hashCode methods in order to make Points hashable.
The method Object.hashCode returns an integer, suitable for use as a hash table key. It is not required that two objects which are not equal (according to the equals method) return different integer results from hashCode but it can improve performance when the integer is used as a key into a data structure. However, any two objects which are equal must return the same integer value from a call to hashCode. Since the default implementation of Object.equals returns true only when two objects are identical, we need to redefine both equals and hashCode to work correctly with objects of type Point. For example, we want two Point objects to test equal when they have the same x and y values, or the same rho and theta values, not just when they refer to the same object. We do this by overriding the methods equals and hashCode in the class Point.
So HashablePoint declares Point's hashCode and equals methods, using Point's rectangular coordinates to generate a hash code and to test for equality. The x and y coordinates are obtained using the appropriate get methods, which ensure the rectangular coordinates are up-to-date before returning their values.
And again, we supply a main method in the aspect for testing.
public aspect HashablePoint {
public int Point.hashCode() {
return (int) (getX() + getY() % Integer.MAX_VALUE);
}
public boolean Point.equals(Object o) {
if (o == this) { return true; }
if (!(o instanceof Point)) { return false; }
Point other = (Point)o;
return (getX() == other.getX()) && (getY() == other.getY());
}
public static void main(String[] args) {
Hashtable h = new Hashtable();
Point p1 = new Point();
p1.setRectangular(10, 10);
Point p2 = new Point();
p2.setRectangular(10, 10);
System.out.println("p1 = " + p1);
System.out.println("p2 = " + p2);
System.out.println("p1.hashCode() = " + p1.hashCode());
System.out.println("p2.hashCode() = " + p2.hashCode());
h.put(p1, "P1");
System.out.println("Got: " + h.get(p2));
}
}
(The code for this example is in InstallDir/examples/tracing.)
Writing a class that provides tracing functionality is easy: a couple of functions, a boolean flag for turning tracing on and off, a choice for an output stream, maybe some code for formatting the output -- these are all elements that Trace classes have been known to have. Trace classes may be highly sophisticated, too, if the task of tracing the execution of a program demands it.
But developing the support for tracing is just one part of the effort of inserting tracing into a program, and, most likely, not the biggest part. The other part of the effort is calling the tracing functions at appropriate times. In large systems, this interaction with the tracing support can be overwhelming. Plus, tracing is one of those things that slows the system down, so these calls should often be pulled out of the system before the product is shipped. For these reasons, it is not unusual for developers to write ad-hoc scripting programs that rewrite the source code by inserting/deleting trace calls before and after the method bodies.
AspectJ can be used for some of these tracing concerns in a less ad-hoc way. Tracing can be seen as a concern that crosscuts the entire system and as such is amenable to encapsulation in an aspect. In addition, it is fairly independent of what the system is doing. Therefore tracing is one of those kind of system aspects that can potentially be plugged in and unplugged without any side-effects in the basic functionality of the system.
Throughout this example we will use a simple application that contains only four classes. The application is about shapes. The TwoDShape class is the root of the shape hierarchy:
public abstract class TwoDShape {
protected double x, y;
protected TwoDShape(double x, double y) {
this.x = x; this.y = y;
}
public double getX() { return x; }
public double getY() { return y; }
public double distance(TwoDShape s) {
double dx = Math.abs(s.getX() - x);
double dy = Math.abs(s.getY() - y);
return Math.sqrt(dx*dx + dy*dy);
}
public abstract double perimeter();
public abstract double area();
public String toString() {
return (" @ (" + String.valueOf(x) + ", " + String.valueOf(y) + ") ");
}
}
TwoDShape has two subclasses, Circle and Square:
public class Circle extends TwoDShape {
protected double r;
public Circle(double x, double y, double r) {
super(x, y); this.r = r;
}
public Circle(double x, double y) { this( x, y, 1.0); }
public Circle(double r) { this(0.0, 0.0, r); }
public Circle() { this(0.0, 0.0, 1.0); }
public double perimeter() {
return 2 * Math.PI * r;
}
public double area() {
return Math.PI * r*r;
}
public String toString() {
return ("Circle radius = " + String.valueOf(r) + super.toString());
}
}