Hello World (AspectJ)

From LiteratePrograms

Jump to: navigation, search
Other implementations: Ada | ALGOL 68 | Alice ML | Amiga E | Applescript | AspectJ | Assembly Intel x86 Linux | Assembly Intel x86 NetBSD | AWK | bash | BASIC | Batch files | C | C, Cairo | C, Xlib | Candle | Clojure | C++ | C# | Delphi | Dylan | E | Eiffel | Erlang | Forth | FORTRAN | Fortress | Go | Groovy | Haskell | Hume | IBM PC bootstrap | Inform 7 | Java | Java, Swing | JavaScript | LaTeX | Lisp | Logo | Lua | Maple | MATLAB | Mercury | OCaml/F Sharp | occam | Oz | Pascal | Perl | PHP | Pic | PIR | PLI | PostScript | Prolog | Python | Rexx | Ruby | Scala | Scheme | Seed7 | sh | Smalltalk | SQL | Standard ML | SVG | Tcl | Tcl Tk | Visual Basic | Visual Basic .NET | XSL

This example shows the classic Java hello world program, extended for AspectJ.

Here's the familiar Hello World Java program:

<<HelloWorld.java>>=
public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello world!");
  }
}

Now let's write an aspect that says "hello" from AspectJ too whenever we run the HelloWorld application.

Aspect declarations look just like class declarations, but using the keyword aspect instead of the keyword class:

<<aspect>>=
public aspect HelloFromAspectJ {
  pointcut
  advice
}

Now we need to give the aspect some content. When an aspect-oriented program runs, join points occur - these represent events in the program execution such as calls to methods, field accesses and so on. We match join points of interest using a pointcut expression. Pointcuts are declared using the pointcut keyword.

<<pointcut>>=
  pointcut mainMethod() : execution(public static void main(String[]));

Since Java is very precise about the signature of a main method, we can write a pointcut that matches the execution join point for any main method. The pointcut above matches the execution of any public, static method that returns void, is called main, and takes a single parameter of type String[]. It doesn't care what type the method is delared in.

Pointcuts on their own don't do anything, but by associating a pointcut expression with advice, we can take action at join points matched by the pointcut.

<<advice>>=
  after() returning : mainMethod() {
    System.out.println("Hello from AspectJ");
  }

The advice says "after returning from the execution of a main method, do this...".

The AspectJ file now becomes:

<<HelloFromAspectJ.aj>>=
aspect

You can compile this example using the AspectJ compiler, ajc.

ajc HelloWorld.java HelloFromAspectJ.aj

Running the program with

java HelloWorld

will produce the output:

Hello world!
Hello from AspectJ
Download code
Views
Personal tools