Home > Articles > Software Development & Management > Object Technology

  • Print
  • + Share This
Like this article? We recommend

A Simple Aspect

Listing 1 shows a simple Java class. They don’t get much simpler than this! This is based on the "Hello World" example included in the AspectJ product. The folder for this is InstallDir\AspectJava\doc\examples\ltw.

Listing 1 A Simple "Hello World" Java Class

public class HelloWorld {
    public static void main (String[] args) {
        System.out.println("Hello World!");

You might not think there’s much of interest in Listing 1. Listing 2 provides our very first aspect. This is contained in the file Tracing.aj in the same folder as HelloWorld.java.

Listing 2 A Tracing Aspect

public aspect Tracing {
    private pointcut mainMethod () :
        execution(public static void main(String[]));

    before () : mainMethod() {
        System.out.println("> Before mainMethod()" + thisJoinPoint);

    after () : mainMethod() {
        System.out.println("< After mainMethod()" + thisJoinPoint);

Don’t worry about the details of Listing 2—we’ll see its purpose in a moment. Let’s build these files, modify the CLASSPATH, and then run the program to learn what it all means. Listing 3 shows these three steps, all executed (as mentioned earlier) from within the ltw folder in the AspectJava\doc\examples folder.

Listing 3 Building and Executing an Aspect

ajc -outjar hello.jar HelloWorld.java
ajc -outjar tracing.jar -outxml Tracing.aj

set classpath=%classpath%;.;.\hello.jar;.\tracing.jar;

aj HelloWorld
> Before mainMethod()execution(void HelloWorld.main(String[]))
Hello World!
< After mainMethod()execution(void HelloWorld.main(String[]))

The last three lines of Listing 3 display the magic of AOP. We have intercepted the normal execution of the HelloWorld Java class at two different entry points:

  • Just before main()—and then main() executes
  • Just after main()

Take a quick look at Listing 2 and compare it with Listing 3 to find the interception. What you’re looking at in Listing 3 is a process called load-time weaving.

  • + Share This
  • 🔖 Save To Your Account