AspectJ

Frequently Asked Questions

Copyright (c) 1997-2001 Xerox Corporation, 2002 Palo Alto Research Center, Incorporated, 2003-2006 Contributors. All rights reserved.

Last updated March 28, 2006

For a list of recently-updated FAQ entries, see Q:What has changed since the last FAQ version?

1 Overview
1. What is AspectJ?
2. What are the benefits of using AspectJ?
3. Can AspectJ work with any Java program?
4. How is AspectJ licensed?
5. What is the AspectJ Project?
2 Quick Start
1. What Java versions does AspectJ require and support?
2. How do I download and install AspectJ?
3. How should I start using AspectJ?
4. How does AspectJ integrate with existing Java development tools?
3 Typical AspectJ programs
1. Are aspects always optional or non-functional parts of a program?
2. What is the difference between development and production aspects?
3. What are some common development aspects?
4. What are some common production aspects?
4 Basic AOP and AspectJ Concepts
1. What are scattering, tangling, and crosscutting?
2. What are join points?
3. What is a pointcut?
4. What is advice?
5. What are inter-type declarations?
6. What is an aspect?
5 Why AOP?
1. Are crosscutting concerns induced by flaws in parts of the system design, programming language, operating system, etc. Or is there something more fundamental going on?
2. Does it really make sense to define aspects in terms of crosscutting?
3. Is AOP restricted to domain-specific applications?
4. Why do I need AOP if I can use interceptors (or JVMPI or ref lection)?
6 Related Technology
1. How does AspectJ compare to other new forms of programming?
2. How do you compare the features of AspectJ with reflective systems?
3. How do AspectJ features compare with those of mixin-based inheritance?
4. How does AspectJ compare with more dynamic AOP?
5. What is the relationship between AOP and XP (extreme programming AKA agile methods)?
6. Will you support C#?
7 Deciding to adopt AspectJ
1. Is it safe to use AspectJ in my product plans?
2. What is the effect of using AspectJ on the source code size of programs?
3. Does AspectJ add any performance overhead?
4. I've heard that AspectJ leads to modularity violations. Does it?
5. Why does AspectJ permit aspects to access and add members of another type? Isn't that violating OO encapsulation?
6. Can I use AspectJ with J2EE?
7. Can I use AspectJ with Generic Java?
8. Can I use AspectJ with J2ME?
9. Are you working to put AOP into Java? It seems that every AOP toolset currently uses proprietary mechanisms to describe point-cuts, etc.
10. What kind of support is available?
11. What mailing lists are there?
8 Using the AspectJ compiler
1. Do I have to use the AspectJ compiler?
2. What files do I need to include when compiling AspectJ programs?
3. I have to list many files in the command line to compile with ajc. Is there any other way to provide the file names to ajc?
4. What Java virtual machine (JVM) do I use to run the AspectJ compiler?
5. How can I use ajc to compile programs for a JVM that is different from the one used to run it?
6. Does the ajc compiler support the assert keyword in Java 1.4?
7. Does the ajc compiler support generics and the other new language features of Java 5?
8. Will aspects work with different versions of the compiler/weaver and runtime?
9. Are there any issues using AspectJ with the Microsoft JVM?
10. Does ajc rely on javac for generating Java bytecode (.class) files?
11. I noticed the AspectJ compiler doesn't use a parser generator. Why is that?
12. How does incremental mode work?
9 Integrating AspectJ into your development environment
1. How do I know which aspects affect a class when looking at that class's source code?
2. What kind of IDE support is available for developing AspectJ programs?
3. What plans are there to support my IDE?
4. Can I port AJDE support to my development environment?
5. I want the aspects for development builds but remove them for production builds. How can I set up the build system so they are unpluggable? And so I use javac in my production build?
6. We compile module jars and then assemble them. Can we continue this with AspectJ?
7. We use modules and would like to use incremental compilation. Is that possible?
10 Programming notes and tips
1. Is it possible to change methods by introducing keywords (like synchronized), adding parameters, or changing the "throws" clause?
2. I don't understand what join points exist. How can I see them?
3. What is the difference between call and execution join points?
4. What is the difference between cflow and cflowbelow?
5. How do I say that I want the topmost entrypoint in a recursive call? How about the most-recent prior entrypoint?
6. What is the difference between constructor call, constructor execution, initialization, and static initialization join points?
7. How do I work with an object right when it is created?
8. I want advice to run at two join points, but it doesn't run at all. What gives?
9. How do I refer to a static field when my advice crosscuts multiple classes?
10. I would like to reuse a type pattern, e.g., to write advice that is limited to a certain set of classes. Do I have to retype it each time?
11. Where do I find example programs and how-to's?
12. Are aspect libraries available?
13. How does ajc interact with the serialVersionUID?
14. How can I use AspectJ with applets?
15. How can I specify types for advice that captures primitives, void, etc.?
16. How do I detect which version I am running?
11 Common Problems
1. When I run, I get a StackOverflowError (or a long stack trace or no output whatsoever)
2. I've declared a field on every class in my package; how do I use it in advice?
3. The AspectJ compiler aborts with an OutOfMemoryError when compiling many classes. How can I fix this?
4. Why do I get a message that my class is already defined?
5. ajc recompiles all files every time. How can I make it recompile only the files that have changed?
6. ajc is using the wrong JVM. How do I fix it?
7. My IDE is trying to parse AspectJ files which makes my project unusable. What can I do?
8. I used to be able to compile my program in my IDE, but when I use AJDE, I run out of memory (or it goes really slow).
9. When I run, I get a NoAspectBoundException or a ClassNotFound message for NoAspectBoundException.
10. My stack traces don't make sense. What gives?
11. My advice is not running (or running twice), and I don't know why.
12. My advice runs for each overridden method!
13. I don't understand when thisEnclosingJoinPointStaticPart is available.
14. I declared a member on a class with package access, but other classes in the package cannot see it.
15. I declared a member on a interface, but javac does not see it.
16. ajc 1.0 complains that it can't find javac. What's wrong?
17. I'm running under 1.4, but ajdoc asks for 1.3 (or throws IllegalAccessError for HtmlWriter.configuration)
18. I set up different files to my compiles to change what the aspects see, but now I don't understand how the aspects are working.
19. I'm reading the code generated by ajc 1.0 in -preprocess mode, and it seems like it would not work (or "like it works this way").
20. I've heard AspectJ can generate or inject code into my code. Is this true?
21. Why can't AspectJ pick out local variables (or array elements or ...)?
22. Why doesn't AspectJ pick out reflective calls? The pointcut call(void run()) won't pick out a call using reflection, like ((Method)run).invoke(null, args).
23. What are the bugs now most affecting users?
24. What extra memory is required at runtime?
12 AspectJ 1.1 and eclipse.org
1. Why did the AspectJ project move to eclipse.org?
2. Do I have to download Eclipse to use AspectJ?
3. What are the relationships between AspectJ, JDT, Eclipse, AJDT, and IDE support generally?
1. What are the new features of AspectJ 5?
2. Should I use code- or annotation-style aspects?
3. What's new about the load-time weaving support in AspectJ 5?
14 Understanding AspectJ Technology
1. Do I need to know how the compiler or weaver works?
2. How does the compiler/weaver work? Are there any white papers?
3. Does AspectJ use reflection at runtime?
4. What about load-time weaving? Can I weave aspects at runtime?
15 AspectJ Project Development
1. I'm interested in the code implementing AspectJ.
2. How can I get involved with developing the AspectJ project?
3. How do I get and compile the source code for AspectJ?
4. How do I build AspectJ and integrate it into AJDT?
5. Where do I find developer documentation on building and testing AspectJ source code?
6. How should I submit test cases for bugs?
7. I'd like to run my test case. How do I get the test harness?
8. BCEL is used by AspectJ but it's not actively developed. Will you change?
16 Getting Help
1. How do I find out more about AspectJ?
2. How do I submit a bug report?
3. How do I communicate with other AspectJ users?
4. How can I search the email archives or the web site?
5. How should I write email queries?
6. How do I write bugs for IDE support?
7. How do I write bugs for the AspectJ compiler?
8. Can you recommend reading or teaching material for AspectJ?
9. Where can our group get consulting and support?
10. What has changed since the last FAQ version?
17 About the AspectJ Project
1. What does the fact that AspectJ is an Open Source Project mean to me?
2. What are your plans to make AspectJ a general feature of Java supported by Sun and the other key players in the Java Industry?
3. When will AspectJ work from class files? When will it work at class-loading time?
4. What are the differences between the current and previously released versions of AspectJ?
5. What is the AspectJ development schedule?
6. Will AspectJ support Java 5?

1 Overview

1. What is AspectJ?

AspectJ(tm) is a simple and practical extension to the Java(tm) programming language that adds to Java aspect-oriented programming (AOP) capabilities. AOP allows developers to reap the benefits of modularity for concerns that cut across the natural units of modularity. In object-oriented programs like Java, the natural unit of modularity is the class. In AspectJ, aspects modularize concerns that affect more than one class.

You compile your program using the AspectJ compiler (perhaps using the supported development environments) and then run it, supplying a small (< 100K) runtime library.

The AspectJ technologies include a compiler (ajc), a debugger (ajdb), a documentation generator (ajdoc), a program structure browser (ajbrowser), and integration with Eclipse, Sun-ONE/Netbeans, GNU Emacs/XEmacs, JBuilder, and Ant.

2. What are the benefits of using AspectJ?

AspectJ can be used to improve the modularity of software systems.

Using ordinary Java, it can be difficult to modularize design concerns such as

  • system-wide error-handling

  • contract enforcement

  • distribution concerns

  • feature variations

  • context-sensitive behavior

  • persistence

  • testing

The code for these concerns tends to be spread out across the system. Because these concerns won't stay inside of any one module boundary, we say that they crosscut the system's modularity.

AspectJ adds constructs to Java that enable the modular implementation of crosscutting concerns. This ability is particularly valuable because crosscutting concerns tend to be both complex and poorly localized, making them hard to deal with.

3. Can AspectJ work with any Java program?

AspectJ has been designed as a compatible extension to Java. By compatible, we mean

upward compatibleAll legal Java programs are legal AspectJ programs.
platform compatible All legal AspectJ programs run on standard Java virtual machines.
tool compatible Existing tools can be extended to work with AspectJ.
programmer compatibleProgramming in AspectJ feels natural to Java programmers.

The AspectJ tools run on any Java 2 Platform compatible platform. The AspectJ compiler produces classes that run on any Java 1.1 (or later) compatible platform.

4. How is AspectJ licensed?

AspectJ 1.5.2 source code and documentation is available under the Eclipse Public License 1.0.

AspectJ 1.1 through 1.5.1 source code and documentation is available under the Common Public License 1.0.

The AspectJ 1.0 tools are open-source software available under the Mozilla Public License 1.1. That documentation is available under a separate license that precludes for-profit or commercial redistribution.

Most users only want to use AspectJ to build programs they distribute. There are no restrictions here. When you distribute your program, be sure to include all the runtime classes from the aspectjrt.jar for that version of AspectJ. When distributing only the runtime classes, you need not provide any notice that the program was compiled with AspectJ or includes binaries from the AspectJ project, except as necessary to preserve the warranty disclaimers in our license.

5. What is the AspectJ Project?

AspectJ is based on over ten years of research at Xerox Palo Alto Research Center as funded by Xerox, a U.S. Government grant (NISTATP), and a DARPA contract.

It has evolved through open-source releases to a strong user community and now operates as an open source project at http://eclipse.org/aspectj The AspectJ team works closely with the community to ensure AspectJ continues to evolve as an effective aspect-oriented programming language and tool set.

The latest release is 1.2 which can be downloaded from the AspectJ project page, including sources as described Q:How do I get and compile the source code for AspectJ?. Development is focused on supporting applications, improving quality and performance, enhancing integration with IDE's, and building the next generations of the language.

2 Quick Start

1. What Java versions does AspectJ require and support?

The AspectJ compiler produces programs for any released version of the Java platform (jdk1.1 and later). When running, your program classes must be able to reach classes in the small (< 100K) runtime library (aspectjrt.jar) from the distribution. The tools themselves require J2SE 1.3 or later to run, but the compiler can produce classes for any 1.1-compliant version of the Java platform.

2. How do I download and install AspectJ?

From AspectJ's web page , download the AspectJ distribution. The jar file is installed by executing

            java -jar jar file name
          

Do not try to extract the jar file contents and then attempt to execute java org.aspectj.tools.Main. (A NoClassDefFoundError exception will be thrown.) The AspectJ distribution is not designed to be installed this way. Use the java -jar form shown above.

To uninstall, remove the files the installer wrote in your file system. In most cases, you can delete the top-level install directory (and all contained files), after you remove any new or updated files you want to keep. On Windows, no registry settings were added or changed, so nothing needs to be undone. Do not install over prior versions, which might have different files. Delete the prior version first.

3. How should I start using AspectJ?

Many users adopt AspectJ in stages, first using it to understand and validate their systems (relying on it only in development) and then using it to implement crosscutting concerns in production systems. AspectJ has been designed to make each step discrete and beneficial.

In order of increasing reliance, you may use AspectJ:

  • In the development process Use AspectJ to trace or log interesting information. You can do this by adding simple AspectJ code that performs logging or tracing. This kind of addition may be removed ("unplugged") for the final build since it does not implement a design requirement; the functionality of the system is unaffected by the aspect.

  • As an ancillary part of your system Use AspectJ to more completely and accurately test the system. Add sophisticated code that can check contracts, provide debugging support, or implement test strategies. Like pure development aspects, this code may also be unplugged from production builds. However, the same code can often be helpful in diagnosing failures in deployed production systems, so you may design the functionality to be deployed but disabled, and enable it when debugging.

  • As an essential part of your system Use AspectJ to modularize crosscutting concerns in your system by design. This uses AspectJ to implement logic integral to a system and is delivered in production builds.

This adoption sequence works well in practice and has been followed by many projects.

4. How does AspectJ integrate with existing Java development tools?

AspectJ products are designed to make it easy to integrate AspectJ into an existing development process. Each release includes Ant tasks for building programs, the AspectJ Development Environment (AJDE) for writing aspects inside popular IDE's, and command-line tools for compiling and documenting Java and AspectJ code.

AspectJ provides replacements for standard Java tools:

  • ajc, the AspectJ compiler, runs on any Java 2 compatible platform, and produces classes that run on any Java 1.1 (or later) compatible platform.

  • ajdoc produces API documentation like javadoc, with additional crosscutting links. For example, it shows advice affecting a particular method or all code affected by a given aspect. At present, ajdoc is only supported in AspectJ 1.0.

For debugging, AspectJ supports JSR-45, which provides a mechanism for debugging .class files that have multiple source files. Debugger clients and VM's are beginning to support this; see Sun's J2SE 1.4.1 VM and jdb debugger and recent versions of JBuilder.

The AspectJ Development Environment (AJDE) enables programmers to view and navigate the crosscutting structures in their programs, integrated with existing support in popular Java IDE's for viewing and navigating object-oriented structures. For many programmers this provides a deeper understanding of how aspects work to modularize their concerns and permits them to extend some of their development practices without having to abandon their existing tools.

AJDE is a set of API's providing the basis for the following development tool integrations:

The common functionality of AJDE is also available in the stand-alone source code browser ajbrowser, included in the tools distribution.

Finally, as mentioned above, AspectJ also supports building with Ant by providing task interfaces to the ajc and ajdoc tools.

3 Typical AspectJ programs

1. Are aspects always optional or non-functional parts of a program?

No. Although AspectJ can be used in a way that allows AspectJ code to be removed for the final build, aspect-oriented code is not always optional or non-functional. Consider what AOP really does: it makes the modules in a program correspond to modules in the design. In any given design, some modules are optional, and some are not.

The examples directory included in the AspectJ distribution contains some examples of the use aspects that are not optional. Without aspects,

beanPoint objects would not be JavaBeans.
introductionPoint objects would not be cloneable, comparable or serializable.
spacewarNothing would be displayed.
telecomNo calls would be billed.

2. What is the difference between development and production aspects?

Production aspects are delivered with the finished product, while development aspects are used during the development process. Often production aspects are also used during development.

3. What are some common development aspects?

Aspects for logging, tracing, debugging, profiling or performance monitoring, or testing.

4. What are some common production aspects?

Aspects for performance monitoring and diagnostic systems, display updating or notifications generally, security, context passing, and error handling.

4 Basic AOP and AspectJ Concepts

1. What are scattering, tangling, and crosscutting?

"Scattering" is when similar code is distributed throughout many program modules. This differs from a component being used by many other components since it involves the risk of misuse at each point and of inconsistencies across all points. Changes to the implementation may require finding and editing all affected code.

"Tangling" is when two or more concerns are implemented in the same body of code or component, making it more difficult to understand. Changes to one implementation may cause unintended changes to other tangled concerns.

"Crosscutting" is how to characterize a concern than spans multiple units of OO modularity - classes and objects. Crosscutting concerns resist modularization using normal OO constructs, but aspect-oriented programs can modularize crosscutting concerns.

2. What are join points?

Join points are well-defined points in the execution of a program. Not every execution point is a join point: only those points that can be used in a disciplined and principled manner are. So, in AspectJ, the execution of a method call is a join point, but "the execution of the expression at line 37 in file Foo.java" is not.

The rationale for restricting join points is similar to the rationale for restricting access to memory (pointers) or restricting control flow expressions (goto) in Java: programs are easier to understand, maintain and extend without the full power of the feature.

AspectJ join points include reading or writing a field; calling or executing an exception handler, method or constructor.

3. What is a pointcut?

A pointcut picks out join points . These join points are described by the pointcut declaration. Pointcuts can be defined in classes or in aspects, and can be named or be anonymous.

4. What is advice?

Advice is code that executes at each join point picked out by a pointcut. There are three kinds of advice: before advice, around advice and after advice. As their names suggest, before advice runs before the join point executes; around advice executes before and after the join point; and after advice executes after the join point. The power of advice comes from the advice being able to access values in the execution context of a pointcut.

5. What are inter-type declarations?

AspectJ enables you to declare members and supertypes of another class in an aspect, subject to Java's type-safety and access rules. These are visible to other classes only if you declare them as accessible. You can also declare compile-time errors and warnings based on pointcuts.

6. What is an aspect?

Aspects are a new class-like language element that has been added to Java by AspectJ. Aspects are how developers encapsulate concerns that cut across classes, the natural unit of modularity in Java.

Aspects are similar to classes because...

  • aspects have type

  • aspects can extend classes and other aspects

  • aspects can be abstract or concrete

  • non-abstract aspects can be instantiated

  • aspects can have static and non-static state and behavior

  • aspects can have fields, methods, and types as members

  • the members of non-privileged aspects follow the same accessibility rules as those of classes

Aspects are different than classes because...

  • aspects can additionally include as members pointcuts, advice, and inter-type declarations;

  • aspects can be qualified by specifying the context in which the non-static state is available

  • aspects can't be used interchangeably with classes

  • aspects don't have constructors or finalizers, and they cannot be created with the new operator; they are automatically available as needed.

  • privileged aspects can access private members of other types

5 Why AOP?

1. Are crosscutting concerns induced by flaws in parts of the system design, programming language, operating system, etc. Or is there something more fundamental going on?

AOP's fundamental assumption is that in any sufficiently complex system, there will inherently be some crosscutting concerns.

So, while there are some cases where you could re-factor a system to make a concern no longer be crosscutting, the AOP idea is that there are many cases where that is not possible, or where doing so would damage the code in other ways.

2. Does it really make sense to define aspects in terms of crosscutting?

Yes.

The short summary is that it is right to define AOP in terms of crosscutting, because well-written AOP programs have clear crosscutting structure. It would be a mistake to define AOP in terms of "cleaning up tangling and scattering", because that isn't particular to AOP, and past programming language innovations also do that, as will future developments.

(Slides for a long talk on this topic were once available at http://www.cs.ubc.ca/~gregor/vinst-2-17-01.zip.)

3. Is AOP restricted to domain-specific applications?

No. Some implementations of AOP are domain-specific, but AspectJ was specifically designed to be general-purpose.

4. Why do I need AOP if I can use interceptors (or JVMPI or ref lection)?

There are many mechanisms people use now to implement some crosscutting concerns. But they don't have a way to express the actual structure of the program so you (and your tools) can reason about it. Using a language enables you to express the crosscutting in first-class constructs. You can not only avoid the maintenance problems and structural requirements of some other mechanisms, but also combine forms of crosscutting so that all the mechanisms for a particular concern are one piece of code.

6 Related Technology

1. How does AspectJ compare to other new forms of programming?

There are many recent proposals for programming languages that provide control over crosscutting concerns. Aspect-oriented programming is an overall framework into which many of these approaches fit. AspectJ is one particular instance of AOP, distinguished by the fact that it was designed from the ground up to be compatible with Java.

For more alternatives for aspect-oriented programming, see http://aosd.net.

2. How do you compare the features of AspectJ with reflective systems?

Reflective and aspect-oriented languages have an important similarity: both provide programming support for dealing with crosscutting concerns. In this sense reflective systems proved that independent programming of crosscutting concerns is possible.

But the control that reflection provides tends to be low-level and extremely powerful. In contrast, AspectJ provides more carefully controlled power, drawing on the rules learned from object-oriented development to encourage a clean and understandable program structure.

3. How do AspectJ features compare with those of mixin-based inheritance?

Some features of AspectJ, such as introduction, are related to mixin-based inheritance. But, in order to support crosscutting, a core goal for AspectJ, AspectJ goes beyond mixin-based inheritance.

Firstly, an aspect imposes behavior on a class, rather than a class requesting behavior from an aspect. An aspect can modify a class without needing to edit that class. This property is sometimes called reverse inheritance.

Secondly, a single aspect can affect multiple classes in different ways. A single paint aspect can add different paint methods to all the classes that know how to paint, unlike mixin classes.

So mixin-based inheritance doesn't have the reverse inheritance property, and mixins affect every class that mixes them in the same. If I want to do something like SubjectObserverProtocol, I need two mixins, SubjectPartofSubjectObserverProtocol and ObserverPartof... In AspectJ, both halves of the protocol can be captured in a single aspect.

4. How does AspectJ compare with more dynamic AOP?

Some AOP techniques are presented as "dynamic" because the weaving occurs when classes are loaded, because aspects can be configured in a separate XML file before launch, or because some advice depends on runtime reflection. They are said to be more flexible than AspectJ.

This is a misconception. First, the AspectJ 1.1 weaver has always supported weaving at compile-time or class-load-time. Weaving at compile-time reduces application launch and running time, and it helps IDE's offer support for tracking down weaving errors and understanding the impact of aspects on a system. On the other hand, weaving at load-time simplifies build and deployment. Before AspectJ 1.2, the user had to write a class loader that used the weaver API to weave at load time; since 1.2, AspectJ comes with a command-line launcher to support weaving at class-load-time without any other changes to a build configuration. In AspectJ 5, we expect to get a similar level of support as AspectWerkz, and to exploit the class bytecode weaving hook available in Java 5 VM's.

Second, AspectJ programs, like Java programs generally, can be written to support any level of XML configuration or to depend on runtime reflection. There are some benefits to using AspectJ; e.g., the proceed() form within around advice simplifies a lot of the work that otherwise would go into writing a generalized interceptor, without introducing many of the runtime errors that can result from interceptors. For AspectJ examples of configurable or reflection-dependent programs, see the sample code linked off the AspectJ documentation page or the examples discussed on the mailing list, e.g., Incremental and runtime weaving support?.

5. What is the relationship between AOP and XP (extreme programming AKA agile methods)?

From a question on the user list:

> Anyone know the connections between AOP and Extreme Programming?
> I am really confused. It seems AOP is a programming paradigm, which
> is the next level of abstraction of OOP. Extreme Programming, however,
> this is a lightweight software development process. One of the common
> motivations of AOP and XP is designed to adopt to the requirement
> changes, so that it can save the cost of software development.
            

This is Raymond Lee's answer:

You're not really that confused. AOP and XP are orthogonal concepts, although AOP can be used to help accomplish XP goals. One of the goals of XP is to respond to changing requirements. Another is to reduce the overall cost of development. These are not necessarily the same thing.

One of the principles of XP that contribute to meeting those goals is to maintain clean, simple designs. One of the criteria for clean, simple designs is to factor out duplication from the code. Benefits of removing duplication include the code being easier to understand, better modularity of the design, lower costs of code changes, less chance of conflicting changes when practicing collective code ownership, etc.

Different types of duplication lend themselves to being addressed by different design paradigms and language features. Duplicate snippets of code can be factored out into methods. Duplicate methods can be factored out to common classes, or pushed up to base classes. Duplicate patterns of methods and their use can be factored out to mechanisms of classes and methods (i.e. instantiations of design patterns).

AOP addresses a type of duplication that is very difficult to handle in the other common paradigms, namely cross-cutting concerns. By factoring out duplicate cross-cutting code into aspects, the target code becomes simpler and cleaner, and the cross-cutting code becomes more centralized and modular.

So, AOP as a paradigm, and the associated tools, gives an XPer, or anyone wanting to remove duplication from the code base, a powerful way to remove a form of duplication not easily addressed until now.

6. Will you support C#?

Not at this time. Although the resemblances between C# and Java means it would probably be a fairly straightforward matter to take the AspectJ language design and produce AspectC#, our current focus is only on supporting effective uses of AspectJ.

7 Deciding to adopt AspectJ

1. Is it safe to use AspectJ in my product plans?

You may use AspectJ in your product or project with little risk. Several factors play a role in reducing the risk of adopting this new technology:

  • AspectJ is an addition to Java, and can be introduced into a project in a way that limits risk. See Q: How should I start using AspectJ? for some suggestions on how to do this.

  • The AspectJ compiler accepts standard Java as input and produces standard Java bytecode as output. In 1.0, an optional mode produces standard Java source code which may then be compiled with any compliant Java compiler (e.g. Sun's javac compiler or IBM's jikes compiler). In 1.1, an optional mode accepts standard Java bytecode from any compliant Java compiler and weaves in the aspects to produce new bytecode.

  • AspectJ is available under a non-proprietary, open source license, either the Mozilla Public License 1.1 for 1.0 or the Common Public License 1.0 for 1.1. AspectJ will continue to evolve and be available, regardless of the fate of any particular organization involved with AspectJ.

  • Removing AspectJ from your program is not difficult, although you will lose the flexibility and economy that AspectJ provided.

2. What is the effect of using AspectJ on the source code size of programs?

Using aspects reduces, as a side effect, the number of source lines in a program. However, the major benefit of using aspects comes from improving the modularity of a program, not because the program is smaller. Aspects gather into a module concerns that would otherwise be scattered across or duplicated in multiple classes.

3. Does AspectJ add any performance overhead?

The issue of performance overhead is an important one. It is also quite subtle, since knowing what to measure is at least as important as knowing how to measure it, and neither is always apparent.

We aim for the performance of our implementation of AspectJ to be on par with the same functionality hand-coded in Java. Anything significantly less should be considered a bug.

There is currently no benchmark suite for AOP languages in general or for AspectJ in particular. It is probably too early to develop such a suite because AspectJ needs more maturation of the language and the coding styles first. Coding styles really drive the development of the benchmark suites since they suggest what is important to measure.

Though we cannot show it without a benchmark suite, we believe that code generated by AspectJ has negligible performance overhead. Inter-type member and parent introductions should have very little overhead, and advice should only have some indirection which could be optimized away by modern VM's.

The ajc compiler will use static typing information to only insert the advice and dynamic pointcut tests that are absolutely necessary. Unless you use 'thisJoinPoint' or 'if', the main dynamic checks will be 'instanceof' checks which are generally quite fast. These checks will only be inserted when they can not be inferred from the static type information.

When measuring performance, write AspectJ code fragments and compare them to the performance of the corresponding code written without AspectJ. For example, don't compare a method with before/after advice that grabs a lock to just the method. That would be comparing apples and oranges. Also be sure to watch out for JIT effects that come from empty method bodies and the like. Our experience is that they can be quite misleading in understanding what you've measured.

4. I've heard that AspectJ leads to modularity violations. Does it?

Well I haven't yet seen a language in which you can't write bad code!

But seriously, most AspectJ users find that just like when they learned OO, it takes a while to really get the hang of it. They tend to start in the usual way, by copying canonical examples and experimenting with variations on them.

But users also find that rather than being dangerous, AspectJ helps them write code that is more clear and has better encapsulation -- once they understand the kind of modularity AspectJ supports. There are several good papers that talk about this (see below), but here's a basic point to keep in mind: when properly used, AspectJ makes it possible program in a modular way, something that would otherwise be spread throughout the code. Consider the following code, adapted from the AspectJ tutorial:

aspect PublicErrorLogging {
    Log log = new Log();

    pointcut publicInterface(Object o):
        call(public * com.xerox.*.*(..)) && target(o);

    after(Object o) throwing (Error e): publicInterface(o) {
        log.write(o, e);
    }
}
          

The effect of this code is to ensure that whenever any public method of an interface or class in the com.xerox package throws an error, that error is logged before being thrown to its caller.

Of course in the alternative implementation a large number of methods have a try/catch around their body.

The AspectJ implementation of this crosscutting concern is clearly modular, whereas the other implementation is not. As a result, if you want to change it, its easier in the AspectJ implementation. For example, if you also want to pass the name of the method, or its arguments to log.write, you only have to edit one place in the AspectJ code.

This is just a short example, but I hope it shows how what happens with AOP and AspectJ is that the usual benefits of modularity are achieved for crosscutting concerns, and that leads to better code, not more dangerous code.

One paper someone else just reminded me of that talks some more about this is: http://www.cs.ubc.ca/~kdvolder/Workshops/OOPSLA2001/submissions/12-nordberg.pdf

5. Why does AspectJ permit aspects to access and add members of another type? Isn't that violating OO encapsulation?

In the spirit of Smalltalk, we have decided to give more power to the language in order to let the user community experiment and discover what is right. To date this has proven to be a successful strategy because it has permitted the construction of many useful aspects that crosscut the internal state of an object, and as such need access the its private members. However, we are not discounting that some sort of restrictions are useful, rather, we are seeking input from the community in order to decide on what these restrictions should be.

In that light, our position on encapsulation is :

  • we respect Java's visibility rules

  • we also provide open-classes, a mature OO technology

  • we provide "privileged" access if you really need it.

Introducing parents or members to classes is a well-studied OO technique known as open classes.

Open classes have been used in many languages prior to AspectJ, including CLOS, Python, Smalltalk, Objective-C, and others. Building from Java, introduction in AspectJ provides better name hygiene and access control than prior languages. Introduced code obeys all of Java's normal accessibility rules for its lexical location in the aspect that it is introduced from. Such code can not even see, much less access, private members of the class it is introduced into. Further, introductions can be declared private to the aspect, so they are not visible to other clients of the class.

Privileged aspects do permit access to private members of another class. They are a response to the very few cases where developers genuinely need such access (typically for testing purposes where it access is necessary), but it would be more risky to open access by putting the aspect in the same package, adding test code, or changing access in the target class. We recommend using privileged aspects only as necessary, and believe that marking them "privileged" makes any potential misuse apparent.

6. Can I use AspectJ with J2EE?

Consider the component types in J2EE:

  • Servlet: AspectJ works well within servlets

  • JSP: It is possible to use AspectJ to affect code in JSPs by precompiling them into Java sources and compiling these with ajc. This can be used, e.g., to customize displays by turning on and off custom JSP taglibs. The mapping from a given jsp source to java package and class name is not standardized, which means doing this imposes dependencies on specific container versions.

  • EJB: AspectJ supports a wide variety of aspects for EJBs. It can be used for logging, tracing, debugging, error handling by layers, correlated method-level interception (e.g., chargebacks), metering, fine-grained transactions, etc. Indeed, it can be used to enforce adherence to coding restrictions within an EJB (e.g., not using java.io, creating a class loader, or listening on sockets) using declare error.

The basic limitations are that there is no built-in support for writing J2EE analogs for AspectJ extensions to Java, like distributed aspects, distributed cflow, or managing state between invocations. These don't prevent one from using AspectJ to do useful intra-container implementation, nor need they prevent one from building distributed support, state management, and inter-component implementations that leverage AspectJ. It just takes some work. In more detail:

All AspectJ implementations may define "code the implementation controls". The AspectJ 1.0 implementation defines this as the files passed to the compiler (AspectJ 1.1 will also support bytecode weaving).

Some advice on EJB operations will generate methods that confuse ejb compilers. To avoid this problem, you can use the -XaddSafePrefix flag when compiling with ajc.

EJB components may be invoked remotely, and containers may passivate and pool EJB's. Servlets have similar limitations, and in both cases the lifespan of the defining class loader is implementation-dependent (though it must span the operation of a particular request).

Being limited by lifecycle and namespace, the AspectJ 1.0 implementation supports aspects that operate through non-remote invocations during the lifetime of the namespace for a particular deployment unit compiled in its entirety by the ajc compiler. This means AspectJ supports common aspects only within a single local runtime namespace (usually implemented as a class loader hierarchy).

Further, AspectJ recognizes language-level join points (object initialization, method calls, etc.), not their EJB analogs (ejb find or create methods...). These lead to the following consequences:

  • Issingleton aspects (the default) are limited to the lifetime of the defining class loader, which in some implementations may not span multiple invocations of the same application or EJB component.

  • EJB lifecycles are different from object lifecycles, so perthis and pertarget aspects will make little sense. They do not work in the current implementation, which uses synchronized methods to ensure a correct association in threaded environments (EJB's may not have synchronized methods).

  • Percflow or percflowbelow aspects are restricted to a chain of non-remote invocations. While EJB 2.0 permits declaring an interface local, this information is not available to the AspectJ compiler today. For same reasons as stated above fore perthis, these will not work even in the EJB container.

  • Evaluation of cflow or cflowbelow pointcuts will be valid only with respect to a chain of non-remote invocations.

In addition, any AspectJ code should respect EJB operations:

  • The EJB container accesses EJB component fields directly, i.e., in code outside the control of the compiler. There is no join point for these accesses, and hence no way to write a pointcut to advise that access.

  • The EJB container may pool EJB components, so any initialization join points may run once per component constructed, not once per component initialized for purposes of a client call.

  • The EJB container is permitted to change class loaders, even between invocations of a particular EJB component (by passivating and activating with a new class loader). In this case, instances of singleton aspects will not operate over multiple invocations of the component, or that static initialization join point recur for a given class as it is re-loaded. This behavior depends on the container implementation.

7. Can I use AspectJ with Generic Java?

We plan to support Generics when Java 1.5 is available.

But at this time, unfortunately not. The two compilers are just not at all compatible. In an ideal world, there would be a wonderful Open Source extensible compiler framework for Java that both GJ and AspectJ would be built on top of, and they would seamlessly interoperate along with all other extensions to Java that you might be interested in, but that's not the case (yet?).

However, on 09 October 2000, the Java Community Process approved a proposal to add generic types to Java that is largely based on GJ (JSR 14). A draft specification was submitted for public review, which closed on 01 August 2001, and a prototype implementation has been released by Sun.

We are committed to moving very rapidly to add support for generic types in AspectJ when generic types become part of the Java language specification. Everyone on the AspectJ team is looking forward to this, because we too would really like to be able to write code that includes both aspects and generic types.

8. Can I use AspectJ with J2ME?

The J2ME platform has several different components. The diagram below shows how the different profiles build on top of the two configurations CDC (Connected Device Configuration) and CLDC (Connected Limited Device Configuration):

    --------------
    |  Personal  |
    --------------      --------
    | Foundation |      | MIDP |
  ------------------  ------------------
  |      CDC       |  |      CLDC      |
------------------------------------------
|                 Java                   |
------------------------------------------  
                
Which configuration you have dictates the restrictions when running AspectJ compiled programs.

If you're running with a profile which sits on top of CDC then there are not, as far as we are aware, any restrictions when running AspectJ compiled code on this flavour of J2ME.

If you're running with a profile sitting on top of CLDC 1.1 you are currently unable to use the thisJoinPoint, thisJoinPointStaticPart and thisEnclosingJoinPointStaticPart variables, the cflow and cflowbelow pointcuts and the percflow and percflowbelow perClauses.

Finally, if you're running with a profile which sits on top of CLDC 1.0 you have all the restrictions of CLDC 1.1. There may be further restrictions due to the lack of types corresponding to the primitive types (e.g. Integer.TYPE), however, at the time of writing we have been unable to do any extensive testing on this.

Note that the aspectj runtime jar is now (as of AspectJ5) quite large but only a small subset is required for executing code in J2ME environments. We plan to ship a second aspectjrt.jar built for the J2ME environment at some point.

For more discussion and to raise any issues you have with AspectJ and J2ME, refer to bugzilla entry 92933.

9. Are you working to put AOP into Java? It seems that every AOP toolset currently uses proprietary mechanisms to describe point-cuts, etc.

We are working on standardization, but it's a question of timing/ripeness (imagine going from thousands of users to millions). (See Q:What are your plans to make AspectJ a general feature of Java supported by Sun and the other key-players in the Java Industry?.) We believe AspectJ addresses this question in the best way possible now:

  • It's open-source. Rather than being proprietary or controlled by a vendor, it's available for anybody to use and build upon, forever.

  • AspectJ is not a set of mechanisms, it's a language. It is currently implemented using certain techniques, but there's nothing that prevents it from being implemented with other techniques. That means users can adopt the language with confidence that implementations will get better.

  • There is no engineering need to change Java. The AspectJ language uses the join point model already in Java, so there is no need to extend the programming model. Our implementation produces valid Java bytecode, which runs in any compliant J2SE VM and supports standard debuggers for those VM's that support JSR-45 (debugging support for multi-language/multi-file sources). This is a huge benefit to Sun since Sun must be extremely cautious about extensions to the language or VM; before adopting AOP, Sun should demand the kind of actual-proof that AspectJ implementations offer.

  • On the issue of "proprietary mechanisms to describe pointcuts, etc.": Any AOP has to have some language to describe pointcuts and the like ("pointcuts" of course being the AspectJ term). Users would like to have one language (to avoid having to learn or transform between many languages) and the choice of multiple implementations (tailored for a configuration, subject to competitive pressure, etc.). That's what AspectJ offers.

  • That said, we believe the AspectJ extensions to Java could form the basis for bringing AOP to Java; when that happens, there will be engineering opportunities to make the implementation and tool support better.

10. What kind of support is available?

The mailing lists provide the primary support for everyone in the community (See Q: What mailing lists are there?). To request commercial support, tutorials, or presentations, use the developer mailing list, aspectj-dev@eclipse.org.

To find out about known issues, see the AspectJ Programming Guide Appendix, "Implementation Notes" and the AspectJ bugs in the database at http://bugs.eclipse.org/bugs (using the product AspectJ). Here are direct links to view open compiler bugs, view all Aspectj bugs (open or closed), or add new bugs.

11. What mailing lists are there?

The AspectJ users mailing list (aspectj-users@eclipse.org) provides an informal network of AspectJ language users who can answer usage questions about AspectJ programs and the AspectJ tools. This is the place to ask how to code something in AspectJ or how to write Ant or shell scripts to invoke the tools.

The AspectJ developers mailing list (aspectj-dev@eclipse.org) provides an informal network of AspectJ technology experts who aim to understand the technology behind AspectJ. The committers to the AspectJ project use this list for open technical and planning discussions. Developers can answer questions about what's possible and about integrating AspectJ technology with other technologies.

For both mailing lists, only subscribed members may post messages. To subscribe, visit the AspectJ web site.

There you can also subscribe to aspectj-announce@eclipse.org, a low-traffic list containing only announcements about significant AspectJ events and product releases. To get on a similar list for aspect-oriented software development generally, see http://aosd.net.

8 Using the AspectJ compiler

1. Do I have to use the AspectJ compiler?

The AspectJ compiler or weaver is required at some point, but many people can use AspectJ without changing their build or deployment process significantly. For aspects that are not required to compile, you can use the AspectJ binary weaver, run at build-time or class-load-time. You can write aspects using the original code style (which must be compiled with the AspectJ compiler) or using the annotation style new in AspectJ 5 (which may be compiled with Javac or the AspectJ compiler).

For more information, see Q:Should I use code- or annotation-style aspects?.

2. What files do I need to include when compiling AspectJ programs?

You need to specify to the compiler the files that contain your aspects and the files that contain the types affected by your aspects. See Q: How do I know which aspects affect a class when looking at that class's source code?. The AspectJ compiler will not search the source path for types that may be affected (unlike Javac and Jikes). In AspectJ 1.0, ajc requires all code to be in source form; in AspectJ 1.1, Java and AspectJ code may be in either source or binary form.

In some cases you should compile your entire system all at once. If this is too slow, then you can try to make reasonable divisions between sets of source files whose aspects do not interact to achieve a shorter compile cycle (particularly for development aspects). If you have aspects that apply to different modules, you can try compiling them into a binary form and using them to weave each module. However, if you get any problems or if you wish to run tests or do a release, you should recompile the entire system.

For more information, see the Development Environment Guide Reference for ajc.

3. I have to list many files in the command line to compile with ajc. Is there any other way to provide the file names to ajc?

Yes, use the argfile option to ajc. List source files in a line-delimited text file and direct ajc to that file using -argfile or @:

ajc @sources.lst
ajc -argfile sources.lst
          

Another way in AspectJ 1.1 is to use the -sourceroots options, which reads all source files in a given set of directories:

ajc -sourceroots "src;testsrc"
          

For more information, see the Development Environment Guide Reference for ajc.

4. What Java virtual machine (JVM) do I use to run the AspectJ compiler?

Use the latest, greatest, fastest JVM you can get your hands on for your platform. The compiler's performance is dependent on the performance of the JVM it is running on, so the faster a JVM you can find to run it on, the shorter your compile times will be. At a minimum you need to use a Java 2 or later JVM to run the compiler (J2SE 1.3 for AspectJ 1.1). We realize that this constraint can be a problem for users who don't currently have a Java 2 JVM available. We're sorry for the inconvenience, but we had to make the hard decision that the advantages of being able to rely on Java 2 were worth the cost of losing a number of developers who are working on platforms without Java 2 support. Here is a list of starting places where you might find support for your system.

The requirement of Java 2 support is only for running the AspectJ compiler. The AspectJ compiler can be used to build programs that will run on Java 1.1 (or probably even on Java 1.0) systems. This means that it can build programs that will run on Macintosh, FreeBSD, and applets that will run in Internet Explorer and Netscape Navigator that are still not yet Java 2 compliant.

5. How can I use ajc to compile programs for a JVM that is different from the one used to run it?

ajc can be used to develop programs that are targeted at the Java 1.1 platform, even though the ajc compiler won't run on that platform. Here's an example of using ajc in this sort of cross-compilation mode (assuming a Windows platform with all the default installation directories):

ajc -target 1.1 -bootclasspath c:\jdk1.1.7\lib\classes.zip \
   -classpath c:\aspectj1.0\lib\aspectjrt.jar -extdirs "" \
   -argfile jdk11system.lst
          

This same technique can be used if you want to run ajc on a JDK 1.3 JVM (highly recommended) but need to generate code for JDK 1.2. That would look something like:

ajc -bootclasspath c:\jdk1.2\jre\lib
t.jar \
   -classpath c:\aspectj1.0\lib\aspectjrt.jar \
    -extdirs c:\jdk1.2\jre\lib\ext
            -argfile jdk12system.lst
          

6. Does the ajc compiler support the assert keyword in Java 1.4?

Yes. As with Javac, use the -source 1.4 option as described in the Development Environment Guide Reference for ajc.

7. Does the ajc compiler support generics and the other new language features of Java 5?

Yes. As with Javac, use the -1.5 option as described in the Development Environment Guide Reference for ajc.

8. Will aspects work with different versions of the compiler/weaver and runtime?

Yes. Both ajc and aspectjrt.jar should work with versions of aspect code and libraries back to AspectJ 1.2.1. Any aspects should be deployed with the same version of aspectjrt.jar they were compiled with. For more information, see the Development Environment Guide Reference for ajc and Deployment notes section on Version compatibility.

9. Are there any issues using AspectJ with the Microsoft JVM?

Since AspectJ requires Java 2 or later, it will not run on the Microsoft JVM, which does not support Java 2.

10. Does ajc rely on javac for generating Java bytecode (.class) files?

No. Some previous versions of AspectJ had this requirement. In AspectJ 1.0, javac can still be used as ajc back end by using the -usejavac flag. You can also run ajc in preprocessor mode to generate Java source (.java) files to be compiled using javac or another java compiler. Neither option is supported in AspectJ 1.1.

11. I noticed the AspectJ compiler doesn't use a parser generator. Why is that?

In AspectJ 1.0, the PARSER for ajc is written by hand. This choice was made with full awareness of the generator tools out there. (Jim had for example used the excellent javacc tool for building the parser for JPython (now Jython)). One of the reasons that AspectJ uses a hand-written parser is that using javacc taught Jim about the LL-k design for parsers (pioneered by antlr). As opposed to the state-machine parsers produced by yacc, these parsers are very readable and writable by humans.

Antlr and javacc did not really suit the project:

  • Antlr's support for unicode in the lexer is still immature and this makes using it with Java challenging. This was an even bigger issue 3 years ago when we started on the Java implementation of ajc.

  • While javacc is freely available, it is not Open Source. Depending on a closed-source tool to build an Open Source compiler would reduce some of the transparency and control of open-source.

There were also several things that were easier to implement with a hand-written parser than with any of the exiting tools.

  • Semi-keywords -- it's important to us that "every legal Java program is also a legal AspectJ program." This wouldn't be true if we made 'before' and 'call' full keywords in AspectJ. It is easier to support these sorts of semi-keywords with a hand-written parser. (Note: ajc-1.0.x handles 'aspect' and 'pointcut' slightly specially which can break a few unusual pure Java programs. This is a compiler limitation that will be fixed in a future release.)

  • Deprecated syntax warnings -- the syntax of AspectJ changed many times from version 0.2 to the 1.0 release. It was easier to provide helpful warning messages for these changes with our hand-written parser.

  • Grammar modularity -- We like being able to have AspectJParser extend JavaParser.

  • Part of the grammar for AspectJ is extremely hard for existing tools to capture. This is the type pattern syntax, i.e. "com.xerox..*.*(..)". The sort of case that gives standard parser generators fits is something like "*1.f(..)" which no one would ever write, but which must be supported for a consistent language.

    In AspectJ 1.1, the parser was written as it is for the underlying Eclipse compiler, with some hand-coding of the sort that avoids adding keywords to the language.

12. How does incremental mode work?

In incremental mode, ajc minimizes the files that need to be recompiled after another file has changed. In Java, only the changed files need to be recompiled, but in AspectJ, other files might also need to be recompiled or re-woven.

Depending on what is modified, we may need to re-weave code.  If you change a pointcut and save it, we currently have to check everywhere in case a new match is occurring or an old match is no longer correct.  However, if you simply change the body of an advice in an aspect, there is (usually) no need to reweave as the affected classes call the advice and the advice (by design) maintains its name in the recompiled aspect.

If you make a change to a class (as opposed to an aspect) and save it, we usually can get away with merely having to compile that class then weave the existing aspects with it - rather than doing a full recompile of the entire system.

There are a lot of possible optimizations to the algorithms we use, by performing more complete analysis of the change made to a file that will enable us to know more accurately whether we need to reweave and if we do then what we need to reweave - we just haven't gotten around to implementing them yet.

9 Integrating AspectJ into your development environment

1. How do I know which aspects affect a class when looking at that class's source code?

When you are working with the IDE support, you can get an understanding of which aspects affect any class. This enables AspectJ programmers to get the benefits of modularizing crosscutting concerns while still having immediate access to what aspects affect a class.

For example, the Development Environment Guide ajbrowser section. shows that you can list or navigate between method and advice affecting that method and between a type and declarations in an aspect on that type. (The IDE support may have more features than ajbrowser, depending on the IDE. See Q: How well does AspectJ integrate with existing Java development tools? for more information on which Java development environments are supported.)

When you are looking at documentation for AspectJ 1.0 programs, ajdoc will provide links from aspects and advice to the affected code, but it provides less information than the IDE support because it only parses declarations.

When you are compiling your program, pointcuts that are statically-determinable can be used in declare statements to identify the code picked out by the pointcut. (A pointcut is statically determinable if it only uses the pointcut designators within, withincode, execution, call, get, set, initialiation, and staticinitialiation.) The compiler will list the static code points which will be affected by any advice specifying the same pointcut. For example, the following will print a warning whereever some code in class Bar gets a field value from Foo:

  declare warning: get(* Foo.*) && within(Bar) 
     : "reading Foo state from Bar";
             

When you are running your program, you can trace advice as it executes. This enables you to identify advice on join points picked out dynamically, which cannot be reflected precisely by IDE support. For a related tracing question, see Q:I don't understand what join points exist. How can I see them?

2. What kind of IDE support is available for developing AspectJ programs?

3. What plans are there to support my IDE?

The AspectJ team directly provided components for JBuilder, Forte, and Emacs and supported the open-source AspectJ plugin project at http://eclipse.org/ajdt which uses the AJDE API support for IDE's. Supporting new IDE's is a matter of building on the AJDE API's, mostly likely adopting one of the existing open-source IDE extensions as a design template. Here are the IDE's where we know people have expressed interest, so interested developer may want to join with others in their developer communities to build the integration.

For questions on AJDE, join the developer's list aspectj-dev@eclipse.org. For questions on the current IDE integrations, contact those projects.

4. Can I port AJDE support to my development environment?

Yes. The core AJDE API is extensible and the source code is available for download. Start by studying the sources for the existing IDE support linked off the AspectJ site http://eclipse.org/aspectj.

5. I want the aspects for development builds but remove them for production builds. How can I set up the build system so they are unpluggable? And so I use javac in my production build?

If you are using development-time-only aspects - aspects that only exist when you are developing the code, not when you ship it - you can use implement a hybrid build process by listing the production source files into a javac-compliant argfile, and the development source files in another ajc argfiles:

     -- file "production.lst":
     One.java
     two/Three.java
     ...

     -- file "tracing.lst":
     trace/Library.java
     Trace.java

     -- file "development.lst":
     @production.lst
     @tracing.lst
          

Then your development build can use ajc:

            ajc @development.lst
          

And your development build can use ajc or javac or jikes:

            jikes @production.lst
          

6. We compile module jars and then assemble them. Can we continue this with AspectJ?

Aspects apply to everything in a namespace, as if everything is compiled together. Sometimes you can break the build down into separate steps without breaking this model, but we haven't stated exactly where it could break because it depends on the interactions between all types. You can try the approaches below, but remember to rebuild everything in one go if there are problems.

The simplest scenario is when the aspects apply to all modules and the modules compile without the aspects. In that case, weaving in the aspects is just the final assembly step for the build.

Next is the case where the aspects make changes to a common library that are visible to other clients, which themselves are otherwise unaffected by the aspects. In this case, the common library can be built using ajc, and used on the classpath for the module builds:


   ajc -outjar common.jar -sourceroots "aspectj-src:src" ...
   cd ../otherProject
   javac -classpath "../common/common.jar:" {src}

		

Combining these last two, there's the case where a common set of aspects should affect two or more modules that are in a dependency relationship to one another. It should work to reuse the aspects in binary form for each compile, in dependency order:


   ajc -outjar common-aspects.jar
       -sourceroots "aspectj-src" ...

   ajc -outjar common.jar
       -sourceroots "src"
       -aspectpath common-aspects.jar ...

   cd ../module1
   ajc -outjar module1.jar
       -sourceroots "src"
       -classpath common.jar
       -aspectpath ../common-aspects.jar ...

   cd ../module2
   ajc -outjar module2.jar
       -sourceroots "src"
       -classpath "common.jar;../module1.jar"
       -aspectpath ../common-aspects.jar ...

		

If two modules are visibly affected by aspects and mutually-dependent, the only thing to do is compile them together.

It's safest to assume that all aspects can affect all types in a namespace; using build boundaries to effect crosscutting limits causes a dangerous dependency on the build process and might cause problems.

7. We use modules and would like to use incremental compilation. Is that possible?

Just incrementally-compile the whole system. Specify to ajc the modules as multiple source roots (or input jars if you are weaving libraries).

In Eclipse's AJDT, you can create a top-level project with symbolic links out to the sources:


   app-assembly/
	 {link common/aspects}
	 {link common/src}
	 {link module1/src}
	 ...

			
Then everything is part of one huge incremental compile. Also, you can close this master project and work the others using the Java compiler or AJDT.

The links make incremental development possible without affecting the modularized Ant builds. (Our practice runs along those lines.)

10 Programming notes and tips

1. Is it possible to change methods by introducing keywords (like synchronized), adding parameters, or changing the "throws" clause?

AspectJ does not enable you to change the signature of a method, but you can (by express declaration) work around some limits imposed by the signature. You can convert a checked exception to unchecked using declare soft, privileged aspects have access to private methods, and you can use a percflow aspect to ferry additional state to a callee without changing intervening signatures. For more details, see The AspectJ Programming Guide. In the case of synchronized, we have what we consider a better solution that uses around advice instead of introduction. This solution is described in this thread (no longer available) on the AspectJ users list, with some additional comments (no longer available) .

2. I don't understand what join points exist. How can I see them?

You can trace them using using an aspect. For example, you can start logging at a particular method call and see what join points occur after the call and before it returns.

Here's some code Jim Hugunin wrote to trace join points and posted to the users list. To reuse the aspect, define a subaspect and implement the pointcuts, for example:


aspect JoinPointSampleAspect extends aj.TraceJoinPoints {
    protected pointcut entry() : 
        execution(static void JoinPointSample.main(String[]));
    protected pointcut exit() : 
        call(static void JoinPointSampleAspect.exit());

    public static void main (String[] args) {
        JoinPointSample.main(args);   
        JoinPointSampleAspect.exit();   
    } 
    public static void exit() {}
}

class JoinPointSample {
    public static void main(String[] args) {}
}
          

Here's the aspect:


/* TraceJoinPoints.java */

package aj;

import org.aspectj.lang.*;
import org.aspectj.lang.reflect.*;
import java.io.*;

public abstract aspect TraceJoinPoints {
    protected abstract pointcut entry();
    protected pointcut exit(): call(* java..*.*(..));
    // this line is for AspectJ 1.1; for 1.0, use "dominates"
    declare precedence : TraceJoinPoints, *;
    final pointcut start(): entry() && !cflowbelow(entry());

    final pointcut trace():
        cflow(entry()) && !cflowbelow(exit()) && !within(TraceJoinPoints+);

    before(): start() { makeLogStream(); }

    before(): trace() { logEnter(thisJoinPointStaticPart); }
    after(): trace() { logExit(thisJoinPointStaticPart); }

    after(): start() { closeLogStream(); }

    //------------ added
    /**
     * Emit a message in the log, e.g.,
     * <pre>TraceJoinPoints tjp = TraceJoinPoints.aspectOf();
     * if (null != tjp) tjp.message("Hello, World!");</pre>
     */
    public void message(String s) {
        out.println("<message>" + prepareMessage(s) + "</message>");
    }
    public void message(String sink, String s) {
        if (null == sink) {
            message(s);
        } else {
            out.println("<message sink=" + quoteXml(sink)
                        + " >" + prepareMessage(s) + "</message>");
        }
    }
    protected String prepareMessage(String s) { return s; } // XXX implement

    //--------- end of added

    PrintStream out;
    int logs = 0;
    protected void makeLogStream() {
        try {
            out = new PrintStream(new FileOutputStream("log" + logs++ + ".xml"));
        } catch (IOException ioe) {
            out = System.err;
        }
    }

    protected void closeLogStream() {
        out.close();
    }


    int depth = 0;
    boolean terminal = false;
    protected void logEnter(JoinPoint.StaticPart jp) {
        if (terminal) out.println(">");
        indent(depth);
        out.print("<" + jp.getKind());
        writeSig(jp);
        writePos(jp);

        depth += 1;
        terminal = true;
    }

    void writeSig(JoinPoint.StaticPart jp) {
        out.print(" sig=");
        out.print(quoteXml(jp.getSignature().toShortString()));
    }

    void writePos(JoinPoint.StaticPart jp) {
        SourceLocation loc = jp.getSourceLocation();
        if (loc == null) return;

        out.print(" pos=");
        out.print(quoteXml(loc.getFileName() +
                           ":" + loc.getLine() +
                           ":" + loc.getColumn()));
    }

    String quoteXml(String s) {
        return "\"" + s.replace('<', '_').replace('>', '_') + "\"";
    }

    protected void logExit(JoinPoint.StaticPart jp) {
        depth -= 1;
        if (terminal) {
            out.println("/>");
        } else {
            indent(depth);
            out.println("</" + jp.getKind() + ">");
        }
        terminal = false;
    }

    void indent(int i) {
        while (i-- > 0) out.print("  ");
    }
}

          

Note that if you are using AspectJ 1.0, the line starting with declare precedence would be removed, and the aspect declaration would look like aspect TraceMyJoinPoints dominates *.

3. What is the difference between call and execution join points?

Briefly, there are two interesting times when a constructor or method is run. Those times are when it is called, and when it actually executes.

The main difference is that a call join point happens outside of the target object (for non-static methods) or class (for static methods and constructors), and that an execution join point happens inside the object or class. This means that the within and withincode pointcuts pick them out differently: A call join point is picked out within the caller, while an execution join point is picked out where it is actually defined.

A call join point is the ``outermost'' join point for a particular call. Once a call join point proceeds, then a number of different things happen. For non-static methods, for example, method dispatch happens, which will cause one method execution join point -- perhaps more, if there are super calls. For constructors, the super constructor is called, and fields are initialized, and then various constructor execution join points will occur.

A call join point matches only the ``external'' calls of a method or constructor, based on a signature, and it does not pick out calls made with super, or this constructor calls.

Here's more detail:

Consider method execution in Java as (1) the initial call from this object to some method on the target object with a particular signature; and (2) the execution of the actual code in the particular method dispatched in the target object. The call join point starts with the initial call and ends when control returns to the call (by return or perhaps thrown exception). The execution join point starts with the method body and ends when the body completes (again by return or throwing an exception), so the execution join point always happens within the bounds of the corresponding call join point. You can see this if you use the join-point tracing aspect in see Q:I don't understand what join points exist. How can I see them?.

As you would expect, the context differs in advice on pointcuts picking out execution and call join points; for call, this refers to the caller, whereas for execution this refers to the called (executing) object.

There are some subtle interactions with other AspectJ semantics. First, the meaning of the signature in the execution() and call() pointcut designators (PCD's) differ: the call type depends upon the type of the reference making the call, while the execution type depends on the enclosing class. Second, you may choose one over another if you cannot bring all your sources within the code the compiler controls (described in the appendix to the Programming Guide). For example, to trace calls into a method from classes which are outside the code the compiler controls at compile time, then using execution() will work while using call()may not. Finally, since super invocations are not considered method calls, to trace super.foo() would require using execution.

Because of differences in the way AspectJ 1.0 and 1.1 are implemented, in 1.0 you should use the call() pointcut designator unless you have a good reason to use execution(); in AspectJ 1.1, the reverse is true.

4. What is the difference between cflow and cflowbelow?

Both pick out all the join points in the control flow of the specified join points. They differ only in that the cflowbelow() pointcut designator does not pick out the join points specified, while cflow() does.

5. How do I say that I want the topmost entrypoint in a recursive call? How about the most-recent prior entrypoint?

This is best seen by way of example. Given a recursive call to int factorial(int) you can print the arguments for (a) the current and most-recent recursive call or (b) the current and original recursive call:

aspect LogFactorial {
    pointcut f(int i) : call(int factorial(int)) && args(i);

    // most-recent
    before(int i, final int j) : f(i) && cflowbelow(f(j)) { 
        System.err.println(i + "-" + j);
    }

    // original
    before(int i, final int j) : f(i) 
        && cflowbelow(cflow(f(j)) && !cflowbelow(f(int))) { 
        System.err.println(i + "@" + j);
    }
}
          

6. What is the difference between constructor call, constructor execution, initialization, and static initialization join points?

Static initialization pertains to initialization of a class or interface type. Constructor call and execution are akin to method call, and initialization generalizes this and picks out the first constructor called.

Their relations are best demonstrated by tracing the join points. Below is the class Test which implements an interface and extends a class along with a trace of the join points below and including the constructor call obtained using TraceJointPoints.java from Q:I don't understand what join points exist. How can I see them?.

            
public class Init {
    public static void main (String[] args) {
        new Test(); 
        end();
    } 
    static void end() {}
}
class Super {}
interface I {}
class Test extends Super implements I {
    Test() {}
}


          

For a program compiled with AspectJ 1.0, the result is this:

            
  <constructor-call sig="Test()" >
    <staticinitialization sig="Super._init_" />
    <staticinitialization sig="Test._init_" />
    <initialization sig="Super()" >
      <instanceinitializer-execution sig="Super._init_" />
      <constructor-execution sig="Super()" />
    </initialization>
    <initialization sig="I()" >
      <instanceinitializer-execution sig="I._init_" />
      <constructor-execution sig="I()" />
    </initialization>
    <initialization sig="Test()" >
      <instanceinitializer-execution sig="Test._init_" />
      <constructor-execution sig="Test()" />
    </initialization>
  </constructor-call>

          

Ordinarily, using a call pointcut designator is best because the call join point surrounds the others, but in the case of constructors there is no target object for the call (because it has not been constructed yet), so you might prefer to use the initialization pointcut designator.

7. How do I work with an object right when it is created?

You can advise some form of constructor join point. Constructors are tricky in Java, and that's exposed in AspectJ. Here are some rules of thumb:

  • If you want the join point on the "outside" of object creation, use after returning from call to the constructor:

        after() returning (Foo newlyCreatedObject): call(Foo.new(..)) { ... }
                  

    You might be tempted to use "this" or "target" to expose the new object, but remember that if you're on the "outside" of object creation, the object itself might not be created yet... it only exists "on the way out", when you return the object.

  • If you want the join point inside a particular constructor, use:

        after(Foo newlyCreatedObject) returning: this(newlyCreatedObject) && execution(Foo.new(..)) { ... }
                  

    Remember, though, that if you use "before" advice here, the body of the constructor will not have run, and so the object may be somewhat uninitialized.

  • In the rare case that there are all sorts of constructors for the object that call each other with this(...) and you want exactly one join point for each initialization of Foo, regardless of the path of constructors it takes, then use:

        after(Foo f) returning: this(f) && initialization(Foo.new(..)) { ... }