posts - 80,comments - 749,trackbacks - 2

The AspectJtm Development Environment Guide

the AspectJ Team

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


This guide describes the tools in the AspectJ 1.2 development environment. See also The AspectJ Programming Guide, the documentation available with the AspectJ support available for various integrated development environments (e.g., Eclipse, Emacs, JBuilder, and NetBeans), and the most-recent documentation available from the AspectJ project page, at

Table of Contents

ajc - compiler and bytecode weaver for the AspectJ and Java languages
ajdoc - generate HTML API documentation, including crosscutting structure (early-access)



ajc — compiler and bytecode weaver for the AspectJ and Java languages


ajc [Options] [file... | @file... | -argfile file...]


The ajc command compiles AspectJ and Java language files, weaving aspects as necessary to produce .class files compliant with any Java VM (1.1 or later). To do bytecode weaving, it also accepts input classes or aspects in binary form.

The arguments after the options specify the source file(s) to compile. (Specify source classes using the -injars or -inpath options, below.) Files may be listed directly on the command line, or listed in a file. The -argfile file and @file forms are equivalent, and are interpreted as meaning all the files listed in the specified file. Each line in these files should contain one option or filename. Comments, as in Java, start with // and extend to the end of the line.

NB: You must explicitly pass ajc all sources necessary for the compilation. When compiling source files containing aspects or pointcuts, be sure to include the source files for any types affected by the aspects or picked out by the pointcuts. (To exclude types from the scope affected by the aspect, change the corresponding pointcut or declaration.) This is necessary because, unlike javac, ajc does not search the sourcepath for classes. You may use the -sourceroots option to specify as source all the .aj and .java files in a set of directory trees.


-injars JarList

deprecated: since 1.2, use -inpath, which also takes directories.

-inpath Path

Accept as source bytecode any .class files in the .jar files or directories on Path. The output will include these classes, possibly as woven with any applicable aspects. Path is a single argument containing a list of paths to zip files or directories, delimited by the platform-specific path delimiter.

-aspectpath JarList

Weave binary aspects from JarList zip files into all sources. The aspects should have been output by the same version of the compiler. To run the output classes requires putting all the aspectpath entries on the run classpath. JarList, like classpath, is a single argument containing a list of paths to jar files, delimited by the platform- specific classpath delimiter.

-argfile File

The file is a line-delimited list of arguments. These arguments are inserted into the argument list.

-outjar output.jar

Put output classes in zip file output.jar.


Run the compiler continuously. After the initial compilation, the compiler will wait to recompile until it reads a newline from the standard input, and will quit when it reads a 'q'. It will only recompile necessary components, so a recompile should be much faster than doing a second compile. This requires -sourceroots.

-sourceroots DirPaths

Find and build all .java or .aj source files under any directory listed in DirPaths. DirPaths, like classpath, is a single argument containing a list of paths to directories, delimited by the platform- specific classpath delimiter. Required by -incremental.


Generate .ajesym symbol files for emacs support


Same as -Xlint:warning (enabled by default)


Set default level for messages about potential programming mistakes in crosscutting code. {level} may be ignore, warning, or error. This overrides entries in org/aspectj/weaver/ from aspectjtools.jar, but does not override levels set using the -Xlintfile option.

-Xlintfile PropertyFile

Specify properties file to set levels for specific crosscutting messages. PropertyFile is a path to a Java .properties file that takes the same property names and values as org/aspectj/weaver/ from aspectjtools.jar, which it also overrides.


Emit information on compiler options and usage


Emit the version of the AspectJ compiler

-classpath Path

Specify where to find user class files. Path is a single argument containing a list of paths to zip files or directories, delimited by the platform-specific path delimiter.

-bootclasspath Path

Override location of VM's bootclasspath for purposes of evaluating types when compiling. Path is a single argument containing a list of paths to zip files or directories, delimited by the platform-specific path delimiter.

-extdirs Path

Override location of VM's extension directories for purposes of evaluating types when compiling. Path is a single argument containing a list of paths to directories, delimited by the platform-specific path delimiter.

-d Directory

Specify where to place generated .class files. If not specified, Directory defaults to the current working dir.

-target [1.1 to 1.4]

Specify classfile target setting (1.1 to 1.4, default is 1.2)


Set compliance level to 1.3


Set compliance level to 1.4 (default)

-source [1.3|1.4]

Toggle assertions (1.3 or 1.4, default is 1.3). When using -source 1.3, an assert() statement valid under Java 1.4 will result in a compiler error. When using -source 1.4, treat assert as a keyword and implement assertions according to the 1.4 language spec.


Emit no warnings (equivalent to '-warn:none') This does not suppress messages generated by declare warning or Xlint.

-warn: items

Emit warnings for any instances of the comma-delimited list of questionable code (eg '-warn:unusedLocals,deprecation'):

    constructorName        method with constructor name
packageDefaultMethod attempt to override package-default method
deprecation usage of deprecated type or member
maskedCatchBlocks hidden catch block
unusedLocals local variable never read
unusedArguments method argument never read
unusedImports import statement not used by code in file
none suppress all compiler warnings
-warn:none does not suppress messages generated by declare warning or Xlint.

Same as -warn:deprecation


Emit no errors for unresolved imports


Keep compiling after error, dumping class files with problem methods


debug attributes level, that may take three forms:

    -g         all debug info ('-g:lines,vars,source')
-g:none no debug info
-g:{items} debug info for any/all of [lines, vars, source], e.g.,

Preserve all local variables during code generation (to facilitate debugging).


Compute reference information.

-encoding format

Specify default source encoding format. Specify custom encoding on a per file basis by suffixing each input source file/folder name with '[encoding]'.


Emit messages about accessed/processed compilation units

-log file

Specify a log file for compiler messages.


Show progress (requires -log mode).


Display speed information.


Do not call System.exit(n) at end of compilation (n=0 if no error)

-repeat N

Repeat compilation process N times (typically to do performance analysis).


(Experimental) produce unwoven class files for input using -injars.


(Experimental) runs weaver in reweavable mode which causes it to create woven classes that can be rewoven, subject to the restriction that on attempting a reweave all the types that advised the woven type must be accessible.


(Experimental) do not inline around advice

-XincrementalFile file

(Experimental) This works like incremental mode, but using a file rather than standard input to control the compiler. It will recompile each time file is changed and and halt when file is deleted.


(Experimental) Normally it is an error to declare aspects Serializable. This option removes that restriction.

File names

ajc accepts source files with either the .java extension or the .aj extension. We normally use .java for all of our files in an AspectJ system -- files that contain aspects as well as files that contain classes. However, if you have a need to mechanically distinguish files that use AspectJ's additional functionality from those that are pure Java we recommend using the .aj extension for those files.

We'd like to discourage other means of mechanical distinction such as naming conventions or sub-packages in favor of the .aj extension.

  • Filename conventions are hard to enforce and lead to awkward names for your aspects. Instead of we recommend using Tracing.aj (or just instead.
  • Sub-packages move aspects out of their natural place in a system and can create an artificial need for privileged aspects. Instead of adding a sub-package like aspects we recommend using the .aj extension and including these files in your existing packages instead.


AspectJ is a compatible extension to the Java programming language. The AspectJ compiler adheres to the The Java Language Specfication, Second Edition and to the The Java Virtual Machine Specification, Second Edition and runs on any Java 2 compatible platform. The code it generates runs on any Java 1.1 or later compatible platform.


Example 1. A simple example

Compile two files:


Example 2. An example using -argfile/@

To avoid specifying file names on the command line, list source files in a line-delimited text argfile. Source file paths may be absolute or relative to the argfile, and may include other argfiles by @-reference. The following file sources.lst contains absolute and relative files and @-references:
Compile the files using either the -argfile or @ form:
ajc -argfile sources.lst
ajc @sources.lst

Argfiles are also supported by jikes and javac, so you can use the files in hybrid builds. However, the support varies:

  • Only ajc accepts command-line options
  • Jikes and Javac do not accept internal @argfile references.
  • Jikes and Javac only accept the @file form on the command line.

Example 3. An example using -injars and -aspectpath

Bytecode weaving using -injars: AspectJ 1.1 supports weaving from input zip or jar files containing class files. Using input jars is like compiling the corresponding source files, and all binaries are emitted to output. Although Java-compliant compilers may differ in their output, ajc should take as input any class files produced by javac, jikes, eclipse, and, of course, ajc. Aspects included in -injars will be woven into like other .class files, but they will specify any crosscutting code (i.e., they will not be woven into other types). To use aspects in their binary form to specify crosscutting, see -aspectpath below.

Aspect libraries using -aspectpath: AspectJ 1.1 supports weaving from read-only libraries containing aspects. Like input jars, they affect all input; unlike input jars, they themselves are not affected or emitted as output. Sources compiled with aspect libraries must be run with the same aspect libraries on their classpath.

The following example builds the tracing example in a command-line environment; it creates a read-only aspect library, compiles some classes for use as input bytecode, and compiles the classes and other sources with the aspect library.

The tracing example is in the AspectJ distribution ({aspectj}/doc/examples/tracing). This uses the following files:


Below, the path separator is taken as ";", but file separators are "/". All commands are on one line. Adjust paths and commands to your environment as needed.

Setup the path, classpath, and current directory:

    cd examples 
export ajrt=../lib/aspectjrt.jar
export CLASSPATH="$ajrt"
export PATH="../bin:$PATH"

Build a read-only tracing library:

    ajc -argfile tracing/tracelib.lst -outjar tracelib.jar 

Build the application with tracing in one step:

    ajc -aspectpath tracelib.jar -argfile tracing/notrace.lst -outjar tracedapp.jar 

Run the application with tracing:

    java -classpath "$ajrt;tracedapp.jar;tracelib.jar" tracing.ExampleMain 

Build the application with tracing from binaries in two steps:

  • (a) Build the application classes (using javac for demonstration's sake):

        mkdir classes 
    javac -d classes tracing/*.java
    jar cfM app.jar -C classes .
  • (b) Build the application with tracing:

        ajc -injars app.jar -aspectpath tracelib.jar -outjar tracedapp.jar 
  • Run the application with tracing (same as above):

        java -classpath "$ajrt;tracedapp.jar;tracelib.jar" tracing.ExampleMain 

    Run the application without tracing:

        java -classpath "app.jar" tracing.ExampleMain

    The AspectJ compiler API

    The AspectJ compiler is implemented completely in Java and can be called as a Java class. The only interface that should be considered public are the public methods in E.g., main(String[] args) takes the the standard ajc command line arguments. This means that an alternative way to run the compiler is

    java [option...] [file...]

    To access compiler messages programmatically, use the methods setHolder(IMessageHolder holder) and/or run(String[] args, IMessageHolder holder).

    Stack Traces and the SourceFile attribute

    Unlike traditional java compilers, the AspectJ compiler may in certain cases generate classfiles from multiple source files. Unfortunately, the original Java class file format does not support multiple SourceFile attributes. In order to make sure all source file information is available, the AspectJ compiler may in some cases encode multiple filenames in the SourceFile attribute. When the Java VM generates stack traces, it uses this attribute to specify the source file.

    (The AspectJ 1.0 compiler also supports the .class file extensions of JSR-45. These permit compliant debuggers (such as jdb in Java 1.4.1) to identify the right file and line even given many source files for a single class. JSR-45 support is planned for ajc in AspectJ 1.1, but is not in the initial release. To get fully debuggable .class files, use the -XnoInline option.)

    Probably the only time you may see this format is when you view stack traces, where you may encounter traces of the format


    where instead of the usual


    format, you see

    File0;File1[Number1];File2[Number2] ... :LineNumber

    In this case, LineNumber is the usual offset in lines plus the "start line" of the actual source file. That means you use LineNumber both to identify the source file and to find the line at issue. The number in [brackets] after each file tells you the virtual "start line" for that file (the first file has a start of 0).

    In our example from the null pointer exception trace, the virtual start line is 1030. Since the file "starts" at line 1000 [1k], the LineNumber points to line 30 of

    So, when faced with such stack traces, the way to find the actual source location is to look through the list of "start line" numbers to find the one just under the shown line number. That is the file where the source location can actually be found. Then, subtract that "start line" from the shown line number to find the actual line number within that file.

    In a class file that comes from only a single source file, the AspectJ compiler generates SourceFile attributes consistent with traditional Java compilers.



    ajdoc — generate HTML API documentation, including crosscutting structure (early-access)


    ajdoc [ -bootclasspath classpathlist ] [ -classpath classpathlist ] [-d path] [-help] [-package] [-protected] [-private] [-public] [-overview overviewFile] [ -sourcepath sourcepathlist ] [-verbose] [-version] [sourcefiles... | packages... | @file... | -argfile file...]


    Similar to javadoc, ajdoc renders HTML documentation for pointcuts, advice, and inter-type declarations, as well as the Java constructs that Javadoc renders. ajdoc also links advice from members affected by the advice and the inter-type declaration for members declared from aspects. The aspect will be fully documented, as will your target classes, including links to any advice or declarations that affect the class. That means, for example, that you can see everything affecting a method when reading the documentation for the method.

    To run ajdoc, use one of the scripts in the AspectJ bin directory. The ajdoc implementation builds on Sun's javadoc command line tool, and you use it in the same way with many of the same options (javadoc options are not documented here; for more information on javadoc usage, see the Javadoc homepage.)

    As with ajc (but unlike javadoc), you pass ajdoc all your aspect source files and any files containing types affected by the aspects; it's often easiest to just pass all the .java files in your system. Unlike ajc, ajdoc will try to find package sources using the specified sourcepath if you list packages on the command line.

    To provide an argfile listing the source files, you can use use the same argfile (@filename) conventions as with ajc. For example, the following documents all the source files listed in argfile.lst, sending the output to the docDir output directory.

    ajdoc -d docDir @argfile.lst
    See the ajc documentation for details on the text file format.

    ajdoc currently requires the tools.jar from J2SE 1.3 to be on the classpath. Normally the scripts set this up, assuming that your JAVA_HOME variable points to an appropriate installation of Java. You may need to provide this jar when using a different version of Java or a JRE.


    Example 4. Documenting Spacewar

    • Change into the examples directory.

    • Type mkdir doc to create the destination directory for the documentation.

    • Type ajdoc -private -d doc spacewar coordination to generate the documentation.

      • (Use -private to get all members, since may of the interesting ones in spacewar are not public.)

    • Type ajdoc -private -d doc @spacewar/demo.lst to use the argfile associated with Spacewar.

    • To view the documentation, open the file index.html in the doc directory using a web browser.

    Chapter 1. AspectJ Browser

    AJBrowser presents a GUI for compiling programs with ajc and navigating crosscutting structure.

    The AspectJ Browser can edit program source files, compile using the AspectJ compiler ajc run a program, and graphically navigate the program's crosscutting structure. For more information on ajc, see The ajc Command-line Reference.

    Launch the browser from the command line either by typing "ajbrowser" to invoke the script in {aspectj}/bin (if AspectJ is installed correctly) or by using the aspectjtools.jar directly, and specifying no arguments or some number of build configuration files (suffix .lst):

      java -jar aspectj1.1/lib/aspectjtools.jar aspectj1.1/doc/examples/spacewar/debug.lst                    

    Building Programs

    Build Configurations

    A build configuration is a set of files to compile for a program (and optionally some additional compile arguments). Because ajc requires all sources to be specified (at least using the -sourceroots option), most users create .lst files that list the files to compile (one argument per line, globbing permitted - for more details, see The ajc Command-line Reference).

    To work with a particular program, select the corresponding ".lst" build configuration file from the GUI using the File menu, "open" item, or by using the "Open Build Configuration" button (). You can populate the build list from the command line by passing any number of ".lst" paths. (However, if you pass in any non-".lst" arguments, it will run the command-line compiler directly.)

    To switch between build configurations, select, add, or remove them using the corresponding toolbar buttons.

    Global build options are stored in an .ajbrowser file in your HOME directory. Edit these from the GUI by clicking the "Options" button or selecting the Tools menu item "Options...". This is how to set classpath, aspectpath, etc.

    The following sections walk through a build.

    Compiling a Program Build Configuration

    To compile click the "Build" button (), or or use the tools menu.

    To build using AspectJ 1.1's incremental mode, click the incremental compile checkbox in the AspectJ Build Options tab of the Options dialog. Once in incremental mode, you can force a full rebuild by holding the shift key down when selecting the build menu item or button.

    You may select from different build configurations in the GUI (see label 1 in the graphic below). (If you get classpath or other errors, set up the global build options as described above.)

    Navigating Program Structure

    Select nodes in the program structure by clicking them (see label 2). If one node is related to one or more other nodes by an association the name of the association will appear below that node and will be displayed in italics. Links to other structure nodes appear in blue below the association. If there is no corresponding source for the link it will appear light-blue.

    Example: Exploring the "Spacewar" sample code

    • Launch ajbrowser

    • Choose "File -> Open" or click the "Open Build Configuration" button () and select the configuration file for debugging the spacewar example, in examples/spacewar/debug.lst.
    • Click the "Build" button () to compile. The left pane should fill with a spacewar declaration tree. If there is a compiler error, the clickable error message shows up as in label 4.

      Note: If you did not set up your classpath, the compile will fail with a message that you need to install aspectjrt.jar on your compile classpath. To do that, select "Tools -> Options" or click the "Options" button (). Click the Build Options tab to view the Build Paths pane. Edit the classpath entry to use your install location. For example, if you ran from the base Aspectj directory, the classpath need only include lib/aspectjrt.jar (though the browser may populate the classpath with the bootclasspath and classpath initially.) Be sure to use the lib/aspectjrt.jar that came with the browser.

    • Different structure views: The structure tree at the left can display different orderings and granularity for structure:

      • The package hierarchy view shows the traditional hierarchy of package, class, and members.
      • The inheritance view shows the hierarchy from topmost parent classes through subclasses to members.
      • The crosscutting view shows the aspect members and the code they affect.
      • Additional buttons in the pane can be used to change the granularity and filter out items.

      Whenever you select an item in the tree view, the source pane scrolls to that item. If you select a leaf item representing another program element, then the tree selection will go to the corresponding node. (See below for how to use two panes to maintain your place.)

    • When working with aspects, it helps to be able to navigate between different program elements:

      • When looking at a method, find the advice that affects it.

      • When looking at a pointcut, find the advice that uses it.

      • When looking at advice, find what it advises - e.g., method calls or executions, initializers, etc.

      • When looking at a type, find any aspects that declare members or supertypes of the type, or vice-versa.

      You can view the advice on a particular method using the default, hierarchical view. Navigate to the tree item for spacewar.Registry.register(SpaceObject) in the debug.lst config file. Now, in the lower, file view, you can see and navigate to the advice using the subtree whose parent is the method affected by relation.

      You can also use crosscutting view to see the advice using a pointcut or the methods affected by advice. For example, to see what advice uses a particular pointcut, navigate to the tree item for the pointcut spacewar.Debug.allConstructorsCut() in the debug.lst config file. You can see and navigate to the advice that uses the pointcut using the pointcut used by relation.

      As an example of seeing the methods affected by advice, while still in the same view, select the first before advice in spacewar.Debug. It has relation sub-trees for both uses pointcut and affects constructions. The affects relations will list different kinds of join points - constructor or method calls, etc.

      Note that the AspectJ browser can only display static structure (whether hierarchical or crosscutting). That means that dynamicly-determined pointcuts (like cflow(pointcut)) will not be shown as picking out static points in source code. Displayable pointcuts roughly correspond to those that can be used in a declare error statement.

    Running Programs

    The browser supports a limited form of running compiled programs. To run programs that have been built, click the run button or select one of the run menu items in the project menu. You can run in the same VM or spawn a new process; the latter is generally better for GUI programs.

    Both require that any classpath you set be specified using platform-specific paths and path separators (the compiler might be more tolerant). Output and error streams will be merged into the streams of the browser (using separate threads, so it may take a few seconds for the pipe threads to gain control.) Errors should be detected and displayed in a dialog.

    The GUI does not support killing a running program, so if your program might hang, be sure to save your files since you may need to kill the browser itself to kill its child processes.

    Isolating problems running the AspectJ browser

    If you have problems with the browser not solved by the documentation, please try to see if you have the same problems when running ajc directly on the command line.

    • If the problem occurs on the command line also, then the problem is not in the browser. (It may be in the compiler; please send bug reports.)

    • If the problem does not occur on the command line, then it may lie in the parameters you are supplying in the build options.

    • If the build options look correct and the problem only occurs when building from the browser, then please submit a bug report.

    Known issues with the AspectJ browser

    For the most up-to-date information on known problems, see the bug database for unresolved compiler bugs or IDE bugs .

    • Memory and forking: Users email most about the browser task running out of memory. This is not a problem with the browser; some compiles take a lot of memory, often more than similar compiles using javac. The browser does not support forking, so the only solution is to edit the java command line or script that launches the browser to add memory.

    • Editing build configuration files: this is not currently supported.

    • The structure model is incomplete after incremental compiles. To get a complete structure model requires a full build.

    • If you change the output directory, you must do a full build.


    • The AJBrowser expects the package and directory structure to match. If they do not it will be unable to browse to the corresponding file.

    • The "Run" feature launches applications in the same VM. As a result, if a Swing application is disposed the AJBrowser will be disposed as well.

    AspectJ Browser questions and bugs

    You can send email to (Do join the list to participate!) We also welcome any bug reports, patches, and feature requests; you can submit them to the bug database at using the AspectJ product and IDE component.

    Chapter 2. AspectJ Ant Tasks


    AspectJ contains a compiler, ajc, that can be run from Ant. Included in the aspectjtools.jar are Ant binaries to support three ways of running the compiler:

    1. AjcTask (iajc), a task to run the new AspectJ 1.1 compiler, which supports all the eclipse and ajc options, including incremental mode.

    2. Ajc11CompilerAdapter (javac), an adapter class to run the new compiler using Javac tasks by setting the build.compiler property

    3. Ajc10 (ajc), a task to run build scripts compatible with the AspectJ 1.0 tasks

    This describes how to install and use the tasks and the adapter. For an example Ant script, see examples/build.xml.

    Installing Ant Tasks

    Install Jakarta Ant 1.5.1: Please see the official Jakarta Ant website for more information and the 1.5.1 distribution. This release is source-compatible with Ant 1.3 and Ant 1.4, but the task sources must be compiled with those versions of the Ant libraries to be used under those versions of Ant. Sources are available under the Common Public License v. 1.0 at

    In Ant, third-party tasks can be declared using a taskdef entry in the build script, to identify the name and classes. When declaring a task, include the aspectjtools.jar either in the taskdef classpath or in ${ANT_HOME}/lib where it will be added to the system class path by the ant script. You may specify the task script names directly, or use the "resource" attribute to specify the default names:


    The current resource file retains the name "ajc" for the Ajc10 task, and uses "iajc" for the AspectJ 1.1 task.

    For more information on using Ant, please refer to Jakarta's documentation on integrating user-defined Ant tasks into builds.

    AjcTask (iajc)

    This task uses the AspectJ 1.1 compiler ajc. The AspectJ compiler can be used like Javac to compile Java sources, but it can also compile AspectJ sources or weave binary aspects with Java bytecode. It can run in normal "batch" mode or in an "incremental" mode, where it only recompiles files it has to revisit. For more information on ajc, see The ajc Command-line Reference.

    Beyond the normal ajc 1.1 compiler options, this task also supports an experimental option for an incremental "tag" file, and it can copy resources from source directories or input jars to the output jar or directory.

    This task is named iajc to avoid conflict with the 1.0 task ajc.

    AjcTask (iajc) Options

    The following tables list the supported parameters. For any parameter specified as a Path, a single path can be specified directly as an attribute, multiple paths can be specified using a nested element of the same name, and a common path can be reused by defining it as a global and passing the id to the corresponding {name}ref attribute. See Path below for more details.

    Most attributes and nested elements are optional. The compiler requires that the same version of aspectjrt.jar be specified on the classpath, and that some sources be be specified (using one or more of sourceroots, injars, inpath, argfiles, and/or srcdir (with patterns)). When in incremental mode, only sourceroots may be specified.

    Boolean parameters default to false unless otherwise stated.

    Table 2.1. AjcTask (iajc) options for specifying sources


    argfiles, argfilesRef (Path)

    An argument file contains a list of arguments read by the compiler. Each line is read into one element of the argument array and may include another argfile by reference.

    sourceRoots, sourceRootsRef (Path)

    Directories containing source files (ending with .java or .aj) to compile.

    srcdir (Path)

    Base directory of sources to compile, assuming there are nested matches. This approach uses the Ant process for matching .java files and is not compatible with incremental mode. Unless using filters to limit the sources included, use sourceroots instead.

    injars, injarsRef (Path)

    Deprecated - use inpath instead. Read .class files for bytecode weaving from zip files (only).

    inpath, inpathRef (Path)

    Read .class files for bytecode weaving from directories or zip files (like classpath).

    classpath, classpathRef (Path)

    The classpath used by the sources being compiled. When compiling aspects, include the same version of the aspectjrt.jar.

    bootclasspath, bootclasspathRef (Path)

    The bootclasspath specifies types to use instead of the invoking VM's when seeking types during compilation.

    extDirs, extDirsRef (Path)

    The extension directories to use instead of those in the invoking VM when seeking types during compilation.

    aspectPath, aspectPathRef (Path)

    Similar to classpath, aspectpath contains read-only, binary aspect libraries that are woven into sources but not included in the output. aspectpath accepts jar/zip files (but, unlike classpath, not directories).

    Table 2.2. AjcTask (iajc) options for specifying output



    The directory in which to place the generated class files. Only one of destDir and outJar may be set.


    The zip file in which to place the generated output class files. Only one of destDir and outJar may be set.


    If true, copy all non-.class files from input jar(s) to the output jar or destination directory after the compile (or incremental compile) completes. In forked mode, this copies only after the process completes, not after incremental compiles.


    When set, copy all files from the sourceroot directories to the output jar or destination directory except those specified in the filter pattern. The pattern should be compatible with an Ant fileset excludes filter; when using this, most developers pass **/CVS/*,**/*.java to exclude any CVS directories or source files.

    Table 2.3. AjcTask (iajc) options for specifying compiler behavior



    Run process in another VM. This gets the forking classpath either explicitly from a forkclasspath entry or by searching the task or system/Ant classpath for the first readable file with a name of the form aspectj{-}tools{.*}.jar. When forking you can specify the amount of memory used with maxmem. Fork cannot be used in incremental mode, unless using a tag file.

    forkclasspath, forkclasspathRef (Path)

    Specify the classpath to use for the compiler when forking.


    The maximum memory to use for the new VM when fork is true. Values should have the same form as accepted by the VM, e.g., "128m".


    incremental mode: Build once, then recompile only required source files when user provides input. Requires that source files be specified only using sourceroots. Incompatible with forking.


    incremental mode: Build once, then recompile only required source files when the tag file is updated, finally exiting when tag file is deleted. Requires that source files be specified only using sourceroots.


    Set experimental option(s), using comma-separated list of accepted options (unlisted here). Options should not contain the leading X. XLint options should be specified using the xlint... entries.


    Experimental option to produce binaries that can only be used as input for the -injars or -inpath option. Usually aspects are compiled normally and put on the aspectpath.

    Table 2.4. AjcTask (iajc) options for specifying compiler side-effects and messages



    If true, emit .ajesym symbol files for Emacs support.


    If true, emit compiler status messages during the compile.


    If true, emit list of file arguments during the compile (but behaves now like verbose).


    If true, do not compile - just print AspectJ version.


    If true, just print help for the command-line compiler.


    Same as xlint:warning: if true, set default level of all language usage messages to warning.


    Specify default level of all language usage messages to one of [error warning ignore].


    Specify property file containing name:level associations setting level for language messages emitted during compilation. Any levels set override the default associations in org/aspectj/weaver/


    If true, throw BuildException to halt build if there are any compiler errors. If false, continue notwithstanding compile errors. Defaults to true.


    Specify a class to use as the message holder for the compile process. The entry must be a fully-qualified name of a class resolveable from the task classpath complying with the org.aspectj.bridge.IMessageHolder interface and having a public no-argument constructor.

    Table 2.5. AjcTask (iajc) options for specifying Eclipse compiler options



    If true, same as warn:none.


    If true, same as warn:deprecation


    One or more comma-separated warning specifications from [constructorName packageDefaultMethod deprecation, maskedCatchBlocks unusedLocals unusedArguments, unusedImports syntheticAccess assertIdentifier].


    If true, same as debug:lines,vars,source


    One or more comma-separated debug specifications from [lines vars source].


    If true, code gen preserves all local variables (for debug purposes).


    If true, emit no errors for unresolved imports.


    If true, compute reference info.


    File to log compiler messages to.


    Default source encoding format (per-file encoding not supported in Ant tasks).


    If true, keep compiling after errors encountered, dumping class files with problem methods.


    If true, emit progress (requires log).


    If true, display speed information.


    Specify target class file format as one of [1.1 1.2]. Defaults to 1.1 class file.


    Set source compliance level to one of [1.3 1.4] (e.g., in 1.4 no assert identifiers and no import from default package). Defaults to 1.3 compliance level.


    Set source assertion mode to one of [1.3 1.4]. Default depends on compliance mode.

    AjcTask matching parameters specified as nested elements

    This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes srcdir) as well as the nested <include>, <exclude>, and <patternset> elements. These can be used to specify source files. However, it is better to use sourceroots to specify source directories unless using filters to exclude some files from compilation.

    AjcTask Path-like Structures

    Some parameters are path-like structures containing one or more elements; these are sourceroots, argfiles, injars, inpath, classpath, bootclasspath, forkclasspath, and aspectpath. In all cases, these may be specified as nested elements, something like this:

    <iajc {attributes..} />
    <pathelement path="{first-location}"/>
    <pathelement path="{second-location}"/>

    As with other Path-like structures, they may be defined elsewhere and specified using the refid attribute:

    <path id="aspect.path">
    <pathelement path="${home}/lib/persist.jar"/>
    <pathelement path="${home}/lib/trace.jar"/>
    <iajc {attributes..} />
    <aspectpath refid="aspect.path"/>

    The task also supports an attribute {name}ref for each such parameter. E.g., for aspectpath:

    <iajc {attributes..} aspectpathref="aspect.path"/>

    Sample of iajc task

    A minimal build script defines the task and runs it, specifying the sources:

    <project name="simple-example" default="compile" >
    <pathelement location="${home.dir}/tools/aspectj/lib/aspectjtools.jar"/>

    <target name="compile" >
    <iajc sourceroots="${home.dir}/ec/project/src"

    Below is script with most everything in it. The compile process...

    1. Runs in incremental mode, recompiling when the user hits return;

    2. Reads all the sources from two directories;

    3. Reads extrinsic module bytecode as input jar for weaving;

    4. Uses a binary aspect library for persistence;

    5. Outputs to an application jar; and

    6. Copies resources from the input jar and source directories into the application jar.

    When this target is built, the compiler will build once and then wait for input from the user. Messages are printed as usual. When the user has quit, then this runs the application.

    <target name="build-test" >
    <iajc outjar="${home.dir}/output/application.jar"
    incremental="true" >
    <pathelement location="${home.dir}/ec/project/src"/>
    <pathelement location="${home.dir}/ec/project/testsrc"/>
    <pathelement location="${home.dir}/ec/int/persist.jar"/>
    <pathelement location="${home.dir}/tools/aspectj/lib/aspectjrt.jar"/>

    <java classname="">
    <pathelement location="${home.dir}/tools/aspectj/lib/aspectjrt.jar"/>
    <pathelement location="${home.dir}/ec/int/persist.jar"/>
    <pathelement location="${home.dir}/output/application.jar"/>

    For an example of a build script, see ../examples/build.xml.

    Programmatically handling compiler messages

    Users may specify a message holder to which the compiler will pass all messages as they are generated. This will override all of the normal message printing, but does not prevent the task from failing if exceptions were thrown or if failonerror is true and the compiler detected errors in the sources.

    Handling messages programmatically could be useful when using the compiler to verify code. If aspects consist of declare [error|warning], then the compiler can act to detect invariants in the code being processed. For code to compare expected and actual messages, see the AspectJ testing module (which is not included in the binary distribution).

    Ajc11CompilerAdapter (javac)

    This CompilerAdapter can be used in javac task calls by setting the build.compiler property. This enables users to to easily switch between the Javac and AspectJ compilers. However, the Javac task's pruning of source files prevents the adapter from doing a correct compile in some cases, so use AjcTask where possible.

    Sample of compiler adapter

    To build using the adapter, put the aspectjtools.jar on the system/ant classpath (e.g., in ${ANT_HOME}/lib) and define the build.compiler property as the fully-qualified name of the class,

    The AspectJ compiler should run for any compile using the Javac task (for options, see the Ant documentation for the Javac task). For example, the call below passes all out-of-date source files in the src/org/aspectj subdirectories to the ajc command along with the destination directory:

    -- command:

    cp aspectj1.1/lib/aspectjtools.jar ant/lib
    ant/bin/ant ...

    -- task invocation in the build script:

    <javac srcdir="src" includes="org/aspectj/**/*.java" destdir="dest" />

    To pass ajc-specific arguments, use a compilerarg entry.

    -- command


    -- build script

    <property name="ajc"

    <javac srcdir="src" includes="org/aspectj/**/*.java" destdir="dest" >
    <compilerarg compiler="${ajc}" line="-argfile src/args.lst"/>

    Compiler adapter compilerarg options

    The adapter supports any ajc command-line option passed using compilerarg, as well as the following options available only in AjcTask. Find more details on the following options in AjcTask (iajc).

    • -Xmaxmem: set maximum memory for forking (also settable in javac).

    • -Xlistfileargs: list file arguments (also settable in javac).

    • -Xfailonerror: throw BuildException on compiler error (also settable in javac).

    • -Xmessageholderclass: specify fully-qualified name of class to use as the message holder.

    • -Xcopyinjars: copy resources from any input jars to output (default behavior since 1.1.1)

    • -Xsourcerootcopyfilter {filter}: copy resources from source directories to output (minus files specified in filter)

    • -Xtagfile {file}: use file to control incremental compilation

    • -Xsrcdir {dir}: add to list of ajc source roots (all source files will be included).

    Special considerations when using Javac and compilerarg:

    • The names above may differ slightly from what you might expect from AjcTask; use these forms when specifying compilerarg.

    • By default the adapter will mimic the Javac task's copying of resource files by specifying "**/CVS/*,**/*.java,**/*.aj" for the sourceroot copy filter. To change this behavior, supply your own value (e.g., "**/*" to copy nothing).

    • Warning - define the system property build.compiler.clean to compile all files, when available. Javac prunes the source file list of "up-to-date" source files based on the timestamps of corresponding .class files, and will not compile if no sources are out of date. This is wrong for ajc which requires all the files for each compile and which may refer indirectly to sources using argument files.

      To work around this, set the global property build.compiler.clean. This tells the compiler adapter to delete all .class files in the destination directory and re-execute the javac task so javac can recalculate the list of source files. e.g.,

      -Dbuild.compiler.clean=anything ...

      Caveats to consider when using this global build.compiler.clean property:

      1. If javac believes there are no out-of-date source files, then the adapter is never called and cannot clean up, and the "compile" will appear to complete successfully though it did nothing.

      2. Cleaning will makes stepwise build processes fail if they depend on the results of the prior compilation being in the same directory, since cleaning deletes all .class files.

      3. This clean process only permits one compile process at a time for each destination directory because it tracks recursion by writing a tag file to the destination directory.

      4. When running incrementally, the clean happens only before the initial compile.

    Ajc10 (ajc)

    This task handles the same arguments as those used by the AspectJ 1.0 task. This should permit those with existing build scripts using the Ajc Ant task to continue using the same scripts when compiling with 1.1. This will list any use of options no longer supported in 1.1 (e.g., lenient, strict, workingdir, preprocess, usejavac,...), and does not provide access to the new features of AspectJ 1.1. (Developers using AspectJ 1.1 only should upgrade their scripts to use AjcTask instead.)

    Ajc10 (ajc) Options

    Most attributes and nested elements are optional. The compiler requires that the same version of aspectjrt.jar be specified on the classpath, and that some sources be be specified (using one or more of argfiles and srcdir (with patterns)).

    Boolean parameters default to false unless otherwise stated.

    Table 2.6. AjcTask (ajc) options for specifying sources



    The base directory of the java files. See


    The target directory for the output .class files


    Comma-separated list of patterns of files that must be included. No files are included when omitted.


    The path to a file containing include patterns.


    Comma-separated list of patterns of files that must be excluded. No files (except default excludes) are excluded when omitted.


    The path to a file containing exclude patterns.


    If true, then default excludes are used. Default excludes are used when omitted (i.e., defaults to true).

    classpath, classpathref

    The classpath to use, optionally given as a reference to a classpath Path element defined elsewhere.

    bootclasspath, bootclasspathref

    The bootclasspath to use, optionally given as a reference to a bootclasspath Path element defined elsewhere.


    Paths to directories containting installed extensions.


    If true, emit debug info in the .class files.


    If true, emit messages about use of deprecated API.


    Emit compiler status messages during the compile.


    Emit version information and quit.


    If true, throw BuildException to halt build if there are any compiler errors. If false, continue notwithstanding compile errors. Defaults to true.


    Value of -source option - ignored unless 1.4.

    Table 2.7. Parameters ignored by the old ajc taskdef, but now supported or buggy



    Default encoding of source files.



    Whether source should be compiled with optimization.



    Generate class files for specific VM version, one of [1.1 1.2].



    Enables dependency-tracking.



    Whether to include the Ant run-time libraries.



    Whether to include the run-time libraries from the executing VM.



    Multi-threaded compilation


    The following table shows that many of the unique parameters in AspectJ 1.0 are no longer supported.

    Table 2.8. Parameters unique to ajc



    comma-delimited list of extended (-X...) options, entered without -X (e.g., X="lint" for -Xlint).


    Generate symbols for Emacs IDE support.


    A comma-delimited list of argfiles that contain a line-delimited list of source file paths (absolute or relative to the argfile).

    argfiles - argument list files

    An argument file is a file (usually {file}.lst) containing a list of source file paths (absolute or relative to the argfile). You can use it to specify all source files to be compiled, which ajc requires to avoid searching every possible source file in the source path when building aspects. If you specify an argfile to the ajc task, it will not include all files in any specified source directory (which is the default behavior for the Javac task when no includes are specified). Conversely, if you specify excludes, they will be removed from the list of files compiled even if they were specified in an argument file.

    The compiler also accepts arguments that are not source files, but the IDE support for such files varies, and Javac does not support them. Be sure to include exactly one argument on each line.

    Ajc10 parameters specified as nested elements

    This task forms an implicit FileSet and supports all attributes of <fileset> (dir becomes srcdir) as well as the nested <include>, <exclude>, and <patternset> elements. These can be used to specify source files.

    ajc's srcdir, classpath, bootclasspath, extdirs, and jvmarg attributes are path-like structures and can also be set via nested <src>, <classpath>, <bootclasspath>, <extdirs>, and <jvmargs> elements, respectively.

    Sample of ajc task

    Following is a declaration for the ajc task and a sample invocation that uses the ajc compiler to compile the files listed in default.lst into the dest dir:

    <project name="example" default="compile" >
    <taskdef name="ajc"
    classname="" >
    <!-- declare classes needed to run the tasks and tools -->
    <pathelement location="${home.dir}/tools/aspectj/lib/aspectjtools.jar"/>

    <target name="compile" >
    <mkdir dir="dest" />
    <ajc destdir="dest" argfiles="default.lst" >
    <!-- declare classes needed to compile the target files -->
    <pathelement location="${home.dir}/tools/aspectj/lib/aspectjrt.jar"/>

    This build script snippet

    <ajc srcdir="${src}"

    compiles all .java files specified in the demo.lst and stores the .class files in the ${build} directory. Unlike the Javac task, the includes attribute is empty by default, so only those files specified in demo.lst are included.

    This next example

    <ajc srcdir="${src}"

    compiles .java files under the ${src} directory in the spacewar and coordination packages, and stores the .class files in the ${build} directory. All source files under spacewar/ and coordination/ are used, except

    See ../examples/build.xml for an example build script.

    Maven support

    Maven is a project-based build system used by Apache and others to integrate many open-source projects. They have a plugin to support AspectJ 1.0, and we plan to help them support AspectJ 1.1. In the meantime, this describes how to upgrade an existing Maven environment to use the AspectJ 1.1 compiler. It was verified on a 1.0-beta10-SNAPSHOT release. For more information on Maven, see

    Sample Maven plugin

    To integrate AspectJ requires writing a Maven plugin and installing the AspectJ libraries in the local Maven repositories directory.

    The Maven plugin defines an "aspectj" goal; given a project with directories "src" and "aspectsrc", the plugin will compile everything using AspectJ. To use the plugin, request the aspectj goal in your project:

    maven aspectj

    The plugin is mainly a Jelly script that specifies Ant scriptlets to run when building with AspectJ. To create your own, start with the files from the Maven support for AspectJ 1.0. (Unfortunately, their plugin version is 1.1. If you want to continue using the old version, copy the files and use a different version number than 1.1 in the examples below.)

    | plugin.jelly
    | project.xml

    Below is a plugin.jelly script that defines the Ant calls. The script uses XML namespace prefixes, so find the start of the Ant compiler call at <ant:iajc .... Note that it uses the existing rule for defining aspectSourcesPresent.

    <?xml version="1.0"?>

    <project xmlns:j="jelly:core"

    <goal name="aspectj"
    description="Compile code with AspectJ"

    <goal name="aspectj:compile"
    description="Compile code with AspectJ">

    <j:if test="${sourcesPresent == 'true'}">
    <ant:available property="aspectSourcesPresent"

    <ant:uptodate property="aspectj.compile.notRequired"
    <ant:srcfiles dir="${}"/>
    <j:if test="${aspectSourcesPresent == 'true'}">
    <ant:srcfiles dir="${}"/>

    <j:set var="aspectjCompileNotRequired"
    <j:if test="${aspectjCompileNotRequired == null}">
    <ant:pathelement path="${plugin.getDependencyPath('aspectj:aspectjtools')}"/>

    <!-- fork to avoid BCEL library version conflict with maven -->

    <ant:pathelement path="${plugin.getDependencyPath('aspectj:aspectjtools')}"/>

    <ant:path refid="maven.compile.src.set"/>
    <ant:pathelement location="${}"/>

    <ant:path refid="maven.dependency.classpath"/>
    <ant:pathelement path="${plugin.getDependencyPath('aspectj:aspectjrt')}"/>

    In this example, no special options are supported, but nicely enough the script can read the library jars from the plugin dependency path:

    <ant:pathelement path="${plugin.getDependencyPath('aspectj:aspectjrt')}"/>

    The plugin dependency path and the filenames of the library jars are defined in the plugin project.xml file. Below are the relevant definitions:






    So the actual paths are calculated from the dependencies, which resolve to the local repository directory of your Maven installation. After you update the Jelly script, manually rename and copy the AspectJ 1.1 libraries to your directory:

    | |---jars
    | aspectj-ant-1.0.6.jar
    | aspectj-ant-1.0.6.jar.md5
    | aspectj-tools-1.0.6.jar
    | aspectj-tools-1.0.6.jar.md5
    | aspectjrt-1.0.6.jar
    | aspectjrt-1.0.6.jar.md5
    | aspectjrt-1.1.jar # add manually
    | aspectjtools-1.1.jar # add manually

    That should be it. Remember to go through the files for any version or library jar name changes. Again, long-term, we hope to the Maven folks can have an official version of the AspectJ plugin which supports both AspectJ 1.0 and 1.1.

    Isolating problems running the Ant tasks

    If you have problems with the tasks not solved by the documentation, please try to see if you have the same problems when running ajc directly on the command line.

    • If the problem occurs on the command line also, then the problem is not in the task. (It may be in the tools; please send bug reports.)

    • If the problem does not occur on the command line, then it may lie in the parameters you are supplying in Ant or in the task's handling of them.

    • If the build script looks correct and the problem only occurs when building from Ant, then please send a report (including your build file, if possible).

    Known issues with the Ant tasks

    For the most up-to-date information on known problems, see the bug database for unresolved compiler bugs or taskdef bugs .

    When running Ant build scripts under Eclipse 2.x variants, you will get a VerifyError because the Eclipse Ant support fails to isolate the Ant runtime properly. To run in this context, set up iajc to fork (and use forkclasspath). Eclipse 3.0 will fork Ant processes to avoid problems like this.

    Memory and forking: Users email most often about the ajc task running out of memory. This is not a problem with the task; some compiles take a lot of memory, often more than similar compiles using javac.

    Forking is now supported in both the Ajc11CompilerAdapter (javac) and AjcTask (iajc), and you can set the maximum memory available. You can also not fork and increase the memory available to Ant (see the Ant documentation, searching for ANT_OPTS, the variable they use in their scripts to pass VM options, e.g., ANT_OPTS=-Xmx128m).

    Ant task questions and bugs

    For questions, you can send email to (Do join the list to participate!) We also welcome any bug reports, patches, and features; you can submit them to the bug database at using the AspectJ product and Ant component.

    posted on 2005-02-20 02:59 Brian Sun 阅读(2129) 评论(0)  编辑  收藏 所属分类: 软件